# Measuring the time properly for nested for-loops with @parallel

**URL:** <https://discourse.julialang.org/t/measuring-the-time-properly-for-nested-for-loops-with-parallel/65841>\
**Category:** Performance\
**Tags:** parallel, time\
**Created:** [August 4, 2021, 9:32pm UTC](https://discourse.julialang.org/t/measuring-the-time-properly-for-nested-for-loops-with-parallel/65841 "2021-08-04T21:32:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rick](https://avatars.discourse-cdn.com/v4/letter/r/9f8e36/32.png) [@Rick](https://discourse.julialang.org/u/Rick)\
**Post date:** [August 4, 2021, 9:32pm UTC](https://discourse.julialang.org/t/measuring-the-time-properly-for-nested-for-loops-with-parallel/65841/1 "2021-08-04T21:32:56Z")

</div>

Hi, I am trying to measure the _total_ time used to execute a nested for-loops. I used `@elapsed` but it seems to only return the time used by one of the inner loops. A MWE is as follows:

```julia
function f(m,n)
    s = SharedArray{Float64}(m)
    for i = 1:m
        @distributed for j = 1:n 
            s[i] = s[i] + rand(1)[1]
        end
    end 
    return s
end

@elapsed f(500, 1e7)

```

The above MWE returns `0.000486948`, which is not what I need because `f(500, 1e7)` takes over a minute to run. I tried the `TickTock` package too and it also has a similar issue.

Therefore, I am wondering what’s the appropriate way to count the time required. In the above MWE, I want to count the time required to run `f(500, 1e7)`, not the time used by one of the loops inside the function `f`.

Thanks for the help in advance!

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [August 4, 2021, 10:13pm UTC](https://discourse.julialang.org/t/measuring-the-time-properly-for-nested-for-loops-with-parallel/65841/2 "2021-08-04T22:13:26Z")

</div>

The macros from `BenchmarkTools` seem to report the correct times:

```julia
julia> using BenchmarkTools

julia> @belapsed f(100,1e6)
4.345676228

julia> @benchmark f(100,1e6)
BechmarkTools.Trial: 2 samples with 1 evaluations.
 Range (min … max): 4.834 s … 4.922 s ┊ GC (min … max): 5.16% … 5.45%
 Time (median): 4.878 s ┊ GC (median): 5.31%
 Time (mean ± σ): 4.878 s ± 62.011 ms ┊ GC (mean ± σ): 5.31% ± 0.21%

  █ ██ 
  █▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█ ▁
  4.83 s Histogram: frequency by time 4.92 s <

 Memory estimate: 8.94 GiB, allocs estimate: 100004891.

```

---

<div class="post-metadata">

**Author:** ![Rick](https://avatars.discourse-cdn.com/v4/letter/r/9f8e36/32.png) [@Rick](https://discourse.julialang.org/u/Rick)\
**Post date:** [August 5, 2021, 2:10am UTC](https://discourse.julialang.org/t/measuring-the-time-properly-for-nested-for-loops-with-parallel/65841/3 "2021-08-05T02:10:15Z")

</div>

This works. Thanks!
