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.0
for i=1:1000000
s += i
end
sleep(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 s and initialize it to 0.

  • Lines 3–5: We loop a variable i through a range starting from 1 to 1000000 and, in each iteration, the current value of i is added to the variable s.

  • Line 6: We block the current task for one second.

  • Line 9: We calculate the absolute time by invoking the built-in @time function.

Example 2: calculating the CPU time

This example shows how to calculate the CPU time of an expression:

using CPUTime
function get_CPU_time()
s = 0.0
for i=1:1000000
s += i
end
sleep(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 s and initialize it to 0.

  • Lines 5–7: We loop a variable i through a range starting from 1 to 1000000 and, in each iteration, the current value of i is added to the variable s.

  • Line 6: We block the current task for one second.

  • Line 9: We calculate the elapsed CPU time by invoking the @CPUtime function.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved