I want to obtain the execution time of a function in Julia. Here is a minimum working example:
function raise_to(n)
for i in 1:n
y = (1/7)^n
end
end
How to obtain the time it took to execute raise_to(10)
?
The recommended way to benchmark a function is to use BenchmarkTools
:
julia> function raise_to(n)
y = (1/7)^n
end
raise_to (generic function with 1 method)
julia> using BenchmarkTools
julia> @btime raise_to(10)
1.815 ns (0 allocations: 0 bytes)
Note that repeating the computation numerous times (like you did in your example) is a good idea to get more accurate measurements. But BenchmarkTools
does it for you.
Also note that BenchmarkTools
avoids many pitfalls of merely using @time
. Most notably with @time
, you're likely to measure compilation time in addition to run time. This is why the first invocation of @time
often displays larger times/allocations:
# First invocation: the method gets compiled
# Large resource consumption
julia> @time raise_to(10)
0.007901 seconds (7.70 k allocations: 475.745 KiB)
3.5401331746414338e-9
# Subsequent invocations: stable and low timings
julia> @time raise_to(10)
0.000003 seconds (5 allocations: 176 bytes)
3.5401331746414338e-9
julia> @time raise_to(10)
0.000002 seconds (5 allocations: 176 bytes)
3.5401331746414338e-9
julia> @time raise_to(10)
0.000001 seconds (5 allocations: 176 bytes)
3.5401331746414338e-9