Time Calculation for Recurring Function Calls

Hi all, I have a function xyz which I call at different positions inside my main function. Is there any way that I could get the cummulative sum of computational time for all the function xyz calls?

There’s the @timed macro that can help. It gives you the return value of the evaluated expression as well as the time it took for evaluation.

total_time = 0.
value, t = @timed rand(3)
total_time += t

But what you are probably actually looking for is a profiler. If you are using VSCode, then you can use the @profview macro, that is documented here. That will give you way better insight into what’s taking how much time in your code.

1 Like

I think the output of @profview might be hard to read for recursive calls. TimerOutputs.jl is probably closer to what you need

1 Like

The easiest way I’ve found is with TimerOutputs.jl. If you have a function:

function xyz(a, b)
  a1 = a^2
  b1 = b^3
  output = a1 + b1
  return output
end

You can modify it like this:

using TimerOutputs

function xyz(a, b)
  @timeit "xyz" begin
      a1 = a^2
      b1 = b^3
      output = a1 + b1
  end
  return output
end

xyz(1, 2)
print_timer()

You can also add @timeit statements to specific lines in the function if you want to drill down.

Thanks. This was exactly what I was looking for. Is there a way to clear the time output so that if i run the function again the time starts from zero

The package Profile has a print function with several options for combining timings in various ways.

1 Like

reset_timer!()

You can find more detailed documentation on the package page: JuliaHub

1 Like