chrono


Usage

Include Header

#include <chrono>

Duration


std::chrono::duration<int,> d(500);  // 500 milliseconds
std::chrono::seconds s(5);                          // 5 seconds
std::chrono::minutes m = std::chrono::minutes(2);  // 2 minutes

Arithmetic on Durations


auto total = s + std::chrono::seconds(10);   // Add durations
auto diff  = m - std::chrono::minutes(1);    // Subtract durations
auto mul   = s * 2;                          // Multiply
auto div   = m / 2;                          // Divide

Accessing Duration Count


auto count = s.count();  // Returns the stored integer (5 in this case)

Time Point


auto now = std::chrono::system_clock::now();          // Current time
std::chrono::time_point<std::chrono::system_clock> tp(now);
    

Time Point Arithmetic


auto future = now + std::chrono::hours(1);          // Add duration
auto past   = now - std::chrono::minutes(30);      // Subtract duration
auto diff   = future - past;                        // Duration between two time points

Conversions


auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(diff);
auto sec = std::chrono::duration_cast<std::chrono::seconds>(diff);
    

Sleep


std::this_thread::sleep_for(std::chrono::seconds(1));   // Sleep for 1 second
std::this_thread::sleep_until(now + std::chrono::minutes(1));  // Sleep until a specific time
    

declaration

  namespace std::chrono {

template<class>> class duration;

template<class> class time_point;

struct system_clock;
struct steady_clock;
struct high_resolution_clock;

} // namespace std::chrono

member types

Member type Definition Explanation
rep Rep Underlying arithmetic type used to store duration count.
period Period Ratio representing the tick period (e.g., std::milli, std::ratio<1>).
duration duration<rep,> Type of this duration.
time_point time_point<clock,> Represents a point in time from a given clock.

member functions

duration

time_point

clocks

utilities