Quantcast
Channel: First steps - JuliaLang
Viewing all articles
Browse latest Browse all 2795

Why does rand() in threads slowdown speed in Julia 1.3

$
0
0

@Sijun wrote:

In Julia 1.3 each thread has its own default global RNG. Calling rand() in each thread is safe. So the following code that calculates pi returns correct result:

function par_pi(n::Int)
    hits = zeros(Int, nthreads())
    @threads for i in 1:n
        x, y = rand(), rand()
        hits[threadid()] += (x^2 + y^2 <= 1)
    end

    4.0 * sum(hits) / n
end
@time par_pi(10_000_000)

But the above code runs 4x slower than the following version that uses manually allocated RNGs:

const threadsRNG = [MersenneTwister() for i in 1:nthreads()]

function par_pi2(n::Int)
    hits = zeros(Int, nthreads())
    @threads for i in 1:n
        rng = threadsRNG[threadid()]
        x, y = rand(rng), rand(rng)
        hits[threadid()] += (x^2 + y^2 <= 1)
    end

    4.0 * sum(hits) / n
end
@time par_pi2(10_000_000)

How to explain it?

Posts: 9

Participants: 3

Read full topic


Viewing all articles
Browse latest Browse all 2795

Trending Articles