# Advice for improving Monte-Carlo code

**URL:** <https://discourse.julialang.org/t/advice-for-improving-monte-carlo-code/49782>\
**Category:** New to Julia\
**Tags:** performance, parallel, monte-carlo\
**Created:** [November 8, 2020, 10:41am UTC](https://discourse.julialang.org/t/advice-for-improving-monte-carlo-code/49782 "2020-11-08T10:41:14Z")\
**Posts on this page:** 1\
**Showing post:** 18

<div class="post-metadata">

**Author:** ![Skoffer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/skoffer/32/378_2.png) [@Skoffer](https://discourse.julialang.org/u/Skoffer)\
**Post date:** [November 8, 2020, 6:21pm UTC](https://discourse.julialang.org/t/advice-for-improving-monte-carlo-code/49782/18 "2020-11-08T18:21:22Z")

</div>

Multi-threading version, which uses random number generation is more involved, it was discussed [here](https://discourse.julialang.org/t/multithreading-and-random-number-generators/49777)

In a simplified version it may look like this

```julia
function meandist3(n, rng)
    d = zeros(Threads.nthreads())
    Threads.@threads for i in 1:n
        k = Threads.threadid()
        x = (rand(rng[k]),rand(rng[k]))
        y = (rand(rng[k]),rand(rng[k]))
        d[k] += sqrt((x[1]-y[1])^2+(x[2]-y[2])^2)
    end
    return sum(d)/n
end

```

And benchmarks

```julia
@btime meandist(100_000_000)
  # 1.690 s (4 allocations: 2.98 GiB)

rngs = Tuple(StableRNG.(2020 .+ collect(1:Threads.nthreads())))
@btime meandist3(100_000_000, $rngs)
  # 1.060 s (43 allocations: 6.13 KiB)

```

It is important, because if you have less then 30Gb it is the only way to run

```julia
julia> @time meandist3(1_000_000_000, rngs)
 13.683740 seconds (44 allocations: 6.141 KiB)
0.5214066471370079

```

EDIT: ha, interestingly enough, `MersenneTwister` suddenly is the best here

```julia
julia> rngs = Tuple(Random.MersenneTwister.(2020 .+ collect(1:Threads.nthreads())))
julia> @time meandist3(1_000_000_000, rngs)
  8.425097 seconds (48 allocations: 6.266 KiB)
0.521398839144987

```

---

_[View the full topic](https://discourse.julialang.org/t/advice-for-improving-monte-carlo-code/49782)._
