How to do flexible timing in Julia?

Another stupid question, in Julia, how to do timing on various parts in the code and display them correspondingly?

For example, a Fortran code like below,

call cpu_time(t0)
 blablabala
call cpu_time(t1)
write(6,*) 't1-t0=', t1-t0
 blabalabla
call cpu_time(t2)
 blablabala
call cpu_time(t3)
write(6,*) 't3-t2=', t3-t2  

Now, from the write(6,*), I can see clearly how much time it took between t0 and t1, t2 and t3.

In Julia is there a similar way so that I can do things similar above?
Like, I know, in Julia one can do

@time begin
 blablabla 
 end

But is there a command such that I can store the time it took in the above block?
Because if I were to do timing for different blocks in the code, I need to store the time it took for each of the block. Finally, I can print those time altogether.

Thanks in advance! Apologize for the stupid question.

You can use the @profile macro to do something similar without having to manually instrument your code.

If you really need times rather than sampled frequencies, you can use TimerOutputs.jl.

1 Like

If you want to do things very manually, you can use time_ns:

julia> t0 = time_ns(); sleep(0.5); t1 = time_ns();

julia> println("My long calculations took $((t1 - t0) / 1e9) seconds")
My long calculations took 0.50197262 seconds

The macro @time is more useful for doing some simple benchmarking, but at least of the order of ~milliseconds:

julia> @time sleep(0.5)
  0.501585 seconds (5 allocations: 144 bytes)

Read carefully the docstring to understand some caveats. Other related macros, @timev, @timed, @elapsed, and @allocated, may be useful, depending on what you really need. @elapsed may be closer to what you asked:

julia> t = @elapsed sleep(0.5)
0.501572848

However for more fine-grained benchmarking you should look into BenchmarkTools.jl. For profiling, instead, see the message above.

3 Likes

Imo, for that, this is the best

3 Likes