For loop Performance

Welcome to the JuliaLang discourse @sam1988!

I’d recommend reading Please read: make it easier to help you for advice on how to format your code and ask questions in a way that makes it more likely for you to get high quality responses which are also useful to others in the future (thought it appears you’ve already got some good replies!).

Furthermore, when benchmarking your code, using @time can be very misleading. In the example you gave, @time mean_loop(rand(10^6),rand(10^6)) will include the time it takes to compile the function mean_loop and the time it takes to create the arrays rand(10^6) and rand(10^6), so most of the time you’re measuring is not actually code relevant to mean_loop. Instead, I would use the @btime macro from BenchmarkTools.jl to properly measure performance like this:

using BenchmarkTools
@btime mean_loop($(rand(10^6)), $(rand(10^6)))

The @btime macro will not include compile time in it’s benchmarks, and it runs the benchmarking function many times so it can give statistically significant results). When I write $(rand(10^6)) inside @btime, that means that I am actually precomputing the array rand(10^6) and pasting the value in as a constant to the function before the benchmark loop is run.

1 Like