Skip to content

Performance of threadsafe rand() #36418

@mbauman

Description

@mbauman

I was surprised at how big a hit we suffer in looking up the THREAD_RNG — even when Julia is started with only 1 thread and without using @threads at all! Is there something we can do here?

julia> using Random, .Threads

julia> nthreads()
1

julia> function serialpi(n)
           inside = 0
           for i in 1:n
               x, y = rand(), rand()
               inside += (x^2 + y^2 <= 1)
           end
           return 4 * inside / n
       end
serialpi (generic function with 1 method)

julia> serialpi(1); @time serialpi(100_000_000);
  0.625890 seconds

julia> function serialpi2(n)
           inside = 0
           rng = Random.THREAD_RNGs[1]
           for i in 1:n
               x, y = rand(rng), rand(rng)
               inside += (x^2 + y^2 <= 1)
           end
           return 4 * inside / n
       end
serialpi2 (generic function with 1 method)

julia> serialpi2(1); @time serialpi2(100_000_000);
  0.257850 seconds

Metadata

Metadata

Assignees

No one assigned

    Labels

    multithreadingBase.Threads and related functionalityperformanceMust go fasterrandomnessRandom number generation and the Random stdlib

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions