Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

julia

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.

like image 841
matthiasbe Avatar asked Mar 05 '21 08:03

matthiasbe


People also ask

How do you store output in variables?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How would you redirect a command stderr to stdout?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.


1 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
like image 111
Bogumił Kamiński Avatar answered Oct 29 '22 18:10

Bogumił Kamiński