How to store the output of @time to a variable?

Viewed 964

Is possible to store the time displayed with @time in a variable ?

For example the following code

for i in 1:10
    @time my_function(i)
end

displays the wall time of my function my_function, but I would like to store the number of milliseconds in an array instead, in order to display it in a plot showing the evolution of the execution time regarding the parameter i.

2 Answers

The simplest is to use @elapsed, e.g.:

julia> [@elapsed rand(5^i) for i in 1:10]
10-element Vector{Float64}:
 3.96e-6
 4.64e-7
 7.55e-7
 3.909e-6
 4.43e-6
 1.5367e-5
 7.0791e-5
 0.000402877
 0.001831287
 0.071062595

and if you use BenchmarkTools.jl then there is also @belapsed macro there for more accurate benchmarking than @elapsed.

EDIT:

  • @time: is printing the time it took to execute, the number of allocations, and the total number of bytes its execution caused to be allocated, before returning the value of the expression. Any time spent garbage collecting (gc) or compiling is shown as a percentage.
  • @elapsed: discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number

I would like to add another example using @elapsed begin to show how it can be used to time multiple lines of code:

dt = @elapsed begin
  x = 1
  y = 2
  z = x^2 + y
  print(z)
end

Additionally, if this is not for benchmarking code and you just want time as an output you can alternatively use time():

t = time()

x = 1
y = 2
z = x^2 + y
print(z)

dt = time() - t
Related