liveBook · Manning

Clock

As explained in C++ Concurrency in Action, Second Edition

A C++ chrono clock is a class that provides a time source, a time-point type, a tick period, and information about whether it is steady.

A C++ chrono clock supplies a time source and defines its time-point type, tick period, and whether it is steady. Call its static now() function to obtain the current time; the result has the clock’s time_point type. section 4.3.1

The clock properties determine how its readings can be interpreted and used:

  • The period typedef gives a fractional-second tick period, but a runtime-varying clock’s observed period is not guaranteed to match it. section 4.3.1
  • A steady clock ticks uniformly and cannot be adjusted. system_clock may move backward when adjusted, so steady clocks are important for timeout calculations. section 4.3.1
  • A time_point counts units of duration from its clock’s epoch. Add or subtract durations to form deadlines; subtract time points from the same clock to measure elapsed time. section 4.3.3
auto start=std::chrono::high_resolution_clock::now();
do_something();
auto stop=std::chrono::high_resolution_clock::now();
std::cout<<"do_something() took "
  <<std::chrono::duration<double,std::chrono::seconds>(stop-start).count()
  <<" seconds"<<std::endl;

This timing example calls high_resolution_clock::now() before and after work, then converts the difference to seconds. section 4.3.3

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Defines clock properties, time-point relationships, and arithmetic, while noting that epochs are not directly queryable.
Examples
Uses system_clock::now(), a 500-nanosecond offset, and high_resolution_clock readings to illustrate clock use.
What you can do after
Apply std::chrono to read clock values, measure elapsed time, and calculate time-based deadlines.
How it connects
Connects clocks to time_point, duration, system_clock, steady_clock, and condition-variable timeouts.

Also explained in

Compare how 5 books explain clock →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.