I’ve always liked the ability to rapidly profile code snippets in Matlab using the ‘tic’ and ‘toc’ commands. I wanted to develop something equally as simple to use in C++ for rapid tests. It turns out that a particularly elegant way to do this is to use RAII techniques, allowing easy profiling of any commands within a scope. A time marker is made on construction, and another time marker is made on destruction, and then compared to the original time marker.
The new ‘chrono’ classes bundles in the C++11 standard library make this task particularly simple. Below is the full class for simple tic toc type profiling …
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Putting this to use is very simple. Just make a new scope using the scope resolution operator and create an instance of TicToc. When it goes out of scope, it will be deleted from the stack and will display the elapsed time.
1 2 3 4 5
Furthermore, other classes can be derived from this simple class, making this a really simple way to get stats on object lifetime.
Enjoy and HAPPY NEW YEAR!