C++ Intermediate · Lesson 09 of 27
std::chrono: timing and durations
Clocks, time points, durations, and typed time literals.
Estimated time · 45–60 min
Learning goals
What you will understand
- Explain std::chrono: timing and durations in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
std::chrono separates three ideas: a clock (steady_clock never jumps backwards, system_clock follows the wall clock), a time_point (a moment) and a duration (a length of time) with a unit. Durations are typed, so mixing seconds and milliseconds is safe and converts correctly.
Use steady_clock for measuring intervals and deadlines. Convert only at the edges with duration_cast. The literals 1ms, 250us and 2s come from std::chrono_literals. ROS 2 timers and rates take std::chrono durations directly.
Guided lesson
Work through these steps
- 1.
Read the std::chrono: timing and durations example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
#include <chrono>
// Header for clocks, time points and durations.
using namespace std::chrono_literals;
// Enable the 10ms / 2s literal suffixes.
const auto start = std::chrono::steady_clock::now();
// Record the current moment on a monotonic clock.
run_step();
// The work being timed.
const auto elapsed = std::chrono::steady_clock::now() - start;
// Subtracting two time points gives a duration.
const auto us = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
// Convert to whole microseconds and read the number.
std::cout << us << " us\n";
// Print how long the step took.
constexpr auto period = 10ms;
// A typed 10-millisecond duration.
constexpr auto seconds = std::chrono::duration<double>(period).count();
// Convert to a double number of seconds (0.01).What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Messages between nodes
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for std::chrono: timing and durations. Expected result: 50 Hz true
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <chrono>
#include <iostream>
#include <thread>
int main() {
using namespace std::chrono_literals;
constexpr auto period = 20ms;
// TODO: convert the period to seconds as a double and print the frequency in Hz (1 / seconds)
const auto start = std::chrono::steady_clock::now();
std::this_thread::sleep_for(10ms);
const auto elapsed = std::chrono::steady_clock::now() - start;
std::cout << std::boolalpha << (elapsed >= 10ms) << '\n';
return 0;
}Expected output
50 Hz
trueStuck? Show the full solution (try it yourself first)
#include <chrono>
#include <iostream>
#include <thread>
int main() {
using namespace std::chrono_literals;
constexpr auto period = 20ms;
const double seconds = std::chrono::duration<double>(period).count();
std::cout << 1.0 / seconds << " Hz\n";
const auto start = std::chrono::steady_clock::now();
std::this_thread::sleep_for(10ms);
const auto elapsed = std::chrono::steady_clock::now() - start;
std::cout << std::boolalpha << (elapsed >= 10ms) << '\n';
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Measure a loop of 1,000 sine calculations with steady_clock and print the elapsed time in microseconds. Then compute the frequency in Hz that corresponds to a 20 ms period.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.