I compared the execution speed of two similar functions, f1 and f2, with f1 taking almost 1000 times longer than f2. Both functions include nested loops. Can anyone explain why there is such a significant difference in execution speed?
(I’m using Julia1.8.3, MacBook Pro with Apple M1 Pro CPU, and macOS Monterey version 12.6)
function f1()
t = 12131
for _ in 1:1000
for _ in 1:t
x = sin(1)
end
end
end
function f2(indexes)
for _ in 1:1000
for _ in indexes
x = sin(1)
end
end
end
@time f1();
@time f1(); # 0.026695 seconds
println()
indexes = 1:12131
@time f2(indexes);
@time f2(indexes); # 0.000004 seconds
I was surprised by the difference between @btime and @time.
So, basically, it seems that the difference comes from the @time’s recompiling time.
(I also checked the outputs of @code_llvm of f3(), f3(1:12131) and f3(indexes).