How to measure the elapsed CPU time in Julia
When evaluating the efficiency of a block of code, there is a distinction made between two concepts:
Absolute Time: This is also known as wall time, real-world time, and wall clock time and refers to the time elapsed when running or executing a specific task. The resulting time is usually expressed in seconds and can be calculated by a chronometer, such as a wristwatch or a wall clock.
CPU Time: This is also known as process time and represents the amount of time taken by the central processing unit (CPU) to evaluate and execute a specific task. On multi-processor machines, the CPU time is computed as the total CPU time for all cores. The Julia package CPUTime.jl measures the elapsed CPU time.
Let's discover the differences between these two concepts using the following examples developed in Julia.
Example 1: calculating the absolute time
This example focuses on calculating the absolute time of an expression:
function get_absolute_time()s = 0.0for i=1:1000000s += iendsleep(1)end@time get_absolute_time()
Explanation
Now, let's explain the code widget above:
Line 1: We define a function called
get_absolute_time.Line 2: We declare a summary variable
sand initialize it to0.Lines 3–5: We loop a variable
ithrough a range starting from1to1000000and, in each iteration, the current value ofiis added to the variables.Line 6: We block the current task for one second.
Line 9: We calculate the absolute time by invoking the built-in
@timefunction.
Example 2: calculating the CPU time
This example shows how to calculate the CPU time of an expression:
using CPUTimefunction get_CPU_time()s = 0.0for i=1:1000000s += iendsleep(1)end@CPUtime get_CPU_time()
Explanation
Now, let's explain the code widget above:
Line 1: We load the Julia package
CPUTime.jl.Line 3: We define a function called
get_CPU_time.Line 4: We declare a summary variable
sand initialize it to0.Lines 5–7: We loop a variable
ithrough a range starting from1to1000000and, in each iteration, the current value ofiis added to the variables.Line 6: We block the current task for one second.
Line 9: We calculate the elapsed CPU time by invoking the
@CPUtimefunction.
Free Resources