liveBook · Manning

Time_point

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

`std::chrono::time_point` is a C++ standard library class template representing a point in time relative to a clock's epoch.

A `std::chrono::time_point` represents a point in time relative to a clock’s epoch. Its template parameters identify the clock and the duration used to measure time since that epoch. The epoch itself is not directly queryable or specified by the C++ Standard. section 4.3.3

Use time points to represent and compare moments:

  • Add a duration to a time point to calculate a future moment, such as a deadline. section 4.3.3
  • Subtract time points from the same clock to get the elapsed duration. section 4.3.3
  • Use time points with timeout operations such as `wait_until` and `try_lock_until`. section 4.3.4
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;

Measure elapsed time by subtracting a start time point from a stop time point, then convert the duration to seconds. section 4.3.3

Listing 4.11. Waiting for a condition variable with a timeout
#include <condition_variable>
#include <mutex>
#include <chrono>
std::condition_variable cv;
bool done;
std::mutex m;
bool wait_loop()
{
    auto const timeout= std::chrono::steady_clock::now()+
        std::chrono::milliseconds(500);
    std::unique_lock<std::mutex> lk(m);
    while(!done)
    {
        if(cv.wait_until(lk,timeout)==std::cv_status::timeout)
            break;
    }
    return done;
}

Set a deadline by adding a duration to the current time, then pass it to a condition variable’s `wait_until` operation. section 4.3.3

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

How deep it goes
Defines clock and duration parameters, epoch-relative values, and arithmetic; notes that epochs cannot be queried or standardized.
Examples
Demonstrates timing a function call and waiting on a condition variable until a deadline.
What you can do after
Apply `std::chrono` to calculate deadlines and measure elapsed time.
How it connects
Connects clocks and durations with condition variables, futures, and timed mutexes.

Also explained in

Compare how 2 books explain time_point →

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.