Measuring elapsed CPU time in Julia
Asked Answered
M

2

15

Many scientific computing languages make a distinction between absolute time (wall clock) and CPU time (processor cycles). For example, in Matlab we have:

>> tic; pause(1); toc
Elapsed time is 1.009068 seconds.

>> start = cputime; pause(1); elapsed = cputime - start
elapsed =
        0

and in Mathematica we have:

>>In[1]:= AbsoluteTiming[Pause[1]]
>>Out[1]= {1.0010572, Null}

>>In[2]:= Timing[Pause[1]]
>>Out[2]= {0., Null}

This distinction is useful when benchmarking code run on computation servers, where there may be high variance in the absolute timing results depending on what other processes are running concurrently.

The Julia standard library provides support for timing of expressions through tic(), toc(), @time and a few other functions/macros all based on time_ns(), a function that measures absolute time.

>>julia> @time sleep(1)
elapsed time: 1.017056895 seconds (135788 bytes allocated)

My question: Is there a simple way to get the elapsed CPU time for an expression evaluation in Julia?

(Side note: doing some digging, it appears that Julia timing is based on the uv_hrtime() function from libuv. It seems to me that using uv_getrusage from the same library might give a way to access elapsed CPU time in Julia, but I'm no expert. Has anybody tried using anything like this?)

Macrobiotics answered 26/6, 2014 at 9:41 Comment(1)
This is a great suggestion. Please file an issue or email the mailing list (or send a pull request if you get something working!)Augmentative
M
14

I couldn't find any existing solutions, so I've put together a package with some simple CPU timing functionality here: https://github.com/schmrlng/CPUTime.jl. The package is completely untested on parallel code and may have other bugs, but if anybody else would like to try it out calling

>> Pkg.clone("https://github.com/schmrlng/CPUTime.jl.git")

from the julia> prompt should install the package.

Macrobiotics answered 27/6, 2014 at 0:44 Comment(0)
B
8

Julia does have the commands tic() and toc() which work just like tic and toc in Matlab:

julia> tic(); 7^1000000000; toc()
elapsed time: 0.046563597 seconds
0.046563597
Bekelja answered 17/4, 2015 at 22:2 Comment(2)
I think this tic() and toc() doesn't work anymore in Julia version 1.1.0 and above. Or I am wrong? What could be the best option apart from the package CPUTime?Herrmann
Those functions were indeed removed. Nowadays, @time and friends do the job. In particular, take a look at @elapsed if you want the time as a variable.Negotiant

© 2022 - 2024 — McMap. All rights reserved.