How to measure the time of a Julia program

Measuring the execution time of a program is considered very important.

The program execution time, also known as digital clock time or wall time, simply refers to the total elapsed time starting from program initiation until program termination.

The program execution time, usually expressed in seconds, helps in analyzing and improving the performance of a program. It also serves to create an effective benchmark report for a program or a block of code.

When benchmarking a program, the generated execution times can be categorized into the following categories:

  • Worst-case execution time (WCET)

  • Best-case execution time (BCET)

  • Average-case execution time (ACET)

Now, let's explore how to measure the execution time of a program using Julia's built-in functions.

Example 1: using the @time function

This function executes an expression and returns its value. It displays the following:

  • The execution time of the expression.

  • The total number of memory allocations.

  • The number of bytes allocated during execution.

This example shows how to extract the execution time using the Julia native @time function:

function get_execution_time()
s = 0.0
for i=1:1000000
s += i
end
sleep(1)
end
@time get_execution_time()

Let's explain the code widget above:

  • Line 1: We define a function called get_execution_time.

  • Line 2: We declare a summary variable s and initialize it to 0.

  • Lines 3–5: We compute the sum of the first one million numbers and store it in the variable s.

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

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

Example 2: using the @timev function

The @timev function is a verbose version of the @time function. It outputs similar information as @time, in addition to any non-zero memory allocation counters.

This example shows how to extract the execution time using the Julia native @timev function:

function get_execution_time()
s = 0.0
for i=1:1000000
s += i
end
sleep(1)
end
@timev get_execution_time()

The code widget above is similar to the one previously elaborated on, apart from the invocation of the @timev function.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved