Modern C++ idoms and recipes

meshell
2,343 views

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.

Exercise

Write a method which measures the execution time of a function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef MODERN_CPP_MEASURE_DURATION_H
#define MODERN_CPP_MEASURE_DURATION_H
#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 {};
};
}
#endif //MODERN_CPP_MEASURE_DURATION_H
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Time intervals

Exercise

Define the durations and intervals (i.e. do the TODOs)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#ifndef MODERN_CPP_TIME_INTERVALS_H
#define MODERN_CPP_TIME_INTERVALS_H
#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);
}
}
#endif //MODERN_CPP_TIME_INTERVALS_H
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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