liveBook · Manning

Std::chrono::duration

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

`std::chrono::milliseconds` is a C++ standard library duration type representing milliseconds.

A `std::chrono::duration` represents a length of time. Its template parameters specify the count’s representation type and the size of each unit in seconds: `std::chrono::milliseconds` is the predefined duration for millisecond counts. section 4.3.2

Predefined duration types include nanoseconds, microseconds, milliseconds, seconds, minutes, and hours. C++14 chrono literals offer concise values such as `30ms`; `duration_cast` converts a duration to another unit. section 4.3.2

std::chrono::milliseconds ms(54802);
std::chrono::seconds s=
    std::chrono::duration_cast<std::chrono::seconds>(ms);

A millisecond count is explicitly converted to seconds with `duration_cast`. section 4.3.2

Durations also specify timeouts for operations such as waiting on futures or condition variables and trying to acquire timed mutexes. section 4.3.4

std::future<int> f=std::async(some_task);
if(f.wait_for(std::chrono::milliseconds(35))==std::future_status::ready)
    do_something_with(f.get());

This example passes a 35-millisecond duration to `future::wait_for` and checks whether the result is ready. section 4.3.4

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

How deep it goes
Defines representation and units through a two-parameter template, then demonstrates aliases, literals, and casting without detailing time points.
Examples
Uses chrono literals for day, minute, and millisecond values, a millisecond-to-second cast, and a future timeout.
What you can do after
Apply durations by constructing values, converting units, and supplying timeouts to timed operations.
How it connects
Connects durations to std::ratio, futures, condition variables, and timed mutexes.

Also explained in

Compare how 2 books explain std::chrono::duration →

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.