Measure execution time - C++ Patterns
← Patterns

Measure execution time

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++98 or newer.

Intent

Measure the execution time of a unit of code.

Description

We introduce the type alias clock on line 5 such that it refers to the std::chrono::steady_clock type. This type represents a monotonic (always increasing) clock.

Before and after the task that we wish to time (line 7 and line 9 respectively), we call the static member function clock::now which gives us a std::chrono::time_point representing the point in time at which it was called. By subtracting the start time point from the end time point on line 11, we get a std::chrono::duration representing the time taken between these time points and, therefore, the execution time of our task.

We can access the value of a std::chrono::duration by calling its count member function. The units of the std::chrono::duration are determined by the clock it came from, but it can be casted to another std::duration with different units with the std::chrono::duration_cast function (or implicitly, if the units are exactly divisible).

Contributors

  • Joseph Mansfield

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share

Feel like contributing? This website is generated from a git repository. If you have something to add or have noticed a mistake, please fork the project on GitHub.

C++ Patterns created by Joseph Mansfield