Measuring performance with the @time macro

Julia comes with a useful macro called @time, which measures the time required to execute code. For example, to measure how long it takes to calculate the sum of 10 million random numbers, we can do the following:

The macro works by inserting code around the code that is being measured. The resulting code may look something like the following:

begin
t1 = now()
result = sum(rand(10_000_000))
t2 = now()
elapsed = t2 - t1
println("It took ", elapsed)
result
end

The new code uses the now() function to take the current time. Then, it executes the user-provided code and captures the result. It takes the current time again, calculates the elapsed time, prints the timing information to the console, and then it returns the result.

Can this be done without metaprogramming? Perhaps we can give that a try. Let's define a function called timeit as follows:

function timeit(func)
t1 = now()
result = func()
t2 = now()
elapsed = t2 - t1
println("It took ", elapsed)
result
end

To use this timing facility, we need to wrap the expression in a function.

This function works fairly well, but the problem is that we have to wrap the code in a separate function before we can measure its performance, which is a hugely inconvenient thing to do. Because of this, we can conclude that having a @time macro is more appropriate.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.174.95