:@elapsed

@elapsed

A macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number.

Examples

  1. Measure the time taken to execute a function:

    julia> function my_function()
              # Some code here
           end
    
    julia> @elapsed my_function()
    0.123456789

    This example measures the time taken to execute the my_function() using the @elapsed macro. The result is the elapsed time in seconds as a floating-point number.

  2. Compare the execution time of two different expressions:

    julia> result1 = @elapsed expression1();
    julia> result2 = @elapsed expression2();
    julia> if result1 < result2
              println("Expression 1 is faster.")
           else
              println("Expression 2 is faster.")
           end

    In this example, we measure the execution time of expression1 and expression2 using the @elapsed macro. We then compare the elapsed times and print a message indicating which expression is faster.

  3. Measure the time taken for a loop to execute:
    julia> @elapsed for i in 1:1000000
              # Loop code here
           end

    This example measures the time taken to execute a loop with 1 million iterations using the @elapsed macro. The result is the elapsed time in seconds as a floating-point number.

Common mistake example:

julia> elapsed_time = @elapsed my_function;
julia> println(elapsed_time);
elapsed_time

In this example, the mistake is not including parentheses () after my_function. Without the parentheses, my_function is treated as a variable rather than a function call, and the @elapsed macro will not correctly measure its execution time. Always make sure to include parentheses when using @elapsed with a function.

See Also

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: