Modern C++ idoms and recipes


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Measure Time Intervals

C++11 provides a flexible date and time library as part of the standard library that allows to define time points and time intervals. The library is called chrono and is available in the <chrono> header in the std::chrono namespace.


Write a method which measures the execution time of a function
#include <chrono>
namespace modern_cpp {
using time_interval_t = std::chrono::microseconds;
template<typename Func, typename... Args>
static time_interval_t duration(Func&& func, Args... args) {
return {};

Time intervals


Define the durations and intervals (i.e. do the TODOs)
#include <chrono>
namespace modern_cpp {
namespace time_intervals {
using namespace std::chrono_literals;
// TODO define the following durations correctly
using day = std::chrono::hours;
using week = std::chrono::hours;
using year = std::chrono::hours;
// TODO define the following intervals correctly
static const std::chrono::hours half_day(1);
static const std::chrono::minutes half_hour(1);
static const std::chrono::seconds half_minute(1);
static const std::chrono::milliseconds half_second(1);
static const std::chrono::microseconds half_millisecond(1);
static const std::chrono::nanoseconds half_microsecond(1);
// TODO define the following intervals based on the type above
static const time_intervals::year week_in_years(1);
static const time_intervals::year day_in_years(1);
static const time_intervals::year hour_in_years(1);
static const time_intervals::year minute_in_years(1);
static const time_intervals::year second_in_years(1);

Bonus exercise

Define user defined literals for day/days and week/weeks and use them together with the chrono literals to define the intervals in the exercise above.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content