Methods to time a block of code in C++ have been well documented, e.g.,
here and here.
In the answers to the questions linked, we usually need to write some lines of code at the start and end of the block of code being timed to start and stop the timer, and then calculate the elapsed time. For convenience, one can make a timing function, and then pass the block of code in as a function.
However, I’m curious to see if it’s possible to make it even simpler by some syntactic sugar that allows me to time a block of code more like an if
or while
block, e.g.,
// some code
time_this_block {
// code to time
}
// some code
This way, I won’t need to put // code to time
in its own separate function and then pass it to a timer function, nor would I need to create various variables of std::chrono
every time I want to time a block. I can simply introduce the time_this_block
with start / stop braces, and that’s it. The time_this_block
(statement? operation? macro?) will have some predefined behaviour, e.g. print the time elapsed to stdout.
Is this, or something similar, possible? If so, how?
2
You can use an RAII class.
Something like (pseudo code):
class BlockTimer {
public:
BlockTimer() {
m_start = std::chrono::steady_clock::now();
}
~BlockTimer() {
auto end = std::chrono::steady_clock::now();
auto duration = (end - start);
std::cout << "duration: " << duration;
}
private:
time_point m_start;
}
Then use it in the following way:
{
BlockTimer btimer;
// ... some code
} // here the scope of `btimer` will end and it will report the duration of the block