I have a large codebase and I want to manually add some timers to profile some sections of the code. Some of those sections are within a loop, so I would like to aggregate all the wall time spent there for each iteration.
What I'd like to do in a Pythonic pseudo-code:
time_step_1 = 0
time_step_2 = 0
for pair in pairs:
start_step_1 = time.now()
run_step_1(pair)
time_step_1 += start_step_1 - time.now()
start_step_2 = time.now()
run_step_2(pair)
time_step_2 += start_step_2 - time.now()
print("Time spent in step 1", time_step_1)
print("Time spent in step 2", time_step_2)
Is there a library in C++ to do this?
Otherwise would you recommend using boost::timer
, create a map of timers and then resume and stop at each iteration?
Not very advanced, but for basic time measurement, you can use
std::chrono
library, specifically thestd::chrono::high_resolution_clock
- the clock with smallest tick period (= highest accuracy) provided by the implementation.For some more trivial time measurement, I have used RAII classes similar to this:
Of course this is a very simple class, which would deserve several improvements before being used for a real measurement.
You can use this class like:
And the output is:
For simple time measurement cases, this might be easier than using a whole timer library, and it's just a few lines of code, you don't need to include lots of headers.