Chrono Library

Overview
Many synchronization classes define functions such as sleep_for(duration) and sleep_until(time_point) APIs. These are called within a thread to relinquish processing for a brief period for synchronization.

Details

standard library defines a new template class ratio to define ratios that can be used only during compile time.ratio is used in chrono library to represent different time units such as millisecond, seconds, hour etc.

Terminology
duration means a fixed number of  time units. A Time unit could be a second or a millisecond or any user defined such as a day or a month. Examples, 10 milliseconds. 2 days etc.

clock is a device that has a starting time or epoch time and a resolution or period. The epoch time can vary based on the clock type. For a wall clock, epoch time starts from  1970.1.1 12:00 GMT. Similarly, the epoch time of a monotonic clock starts from system boot time. The  resolution or period of the clock is expressed in time units. It means time taken for 1 clock tick. For a wall clock the period can be 100 nanoseconds and for monotonic clock it can be 1 nanosecond. Also monotonic clocks are steady, does not go forward or backward due to external events such as day light savings. 

time_point is associated with a clock . It represents the duration  since epoch time of the clock. For a wall clock, time_point for 2018.09.21 11:58:00 would be 1537511280 seconds. Similarly, for a monotonic clock, now() would return duration since system boot. By default, time units are same the Period of the clock but it can be changed.

The following diagram describes the relationships between clock, duration and timepoint.


duration means a fixed number of  time units. A Time unit could be a second or a millisecond or any user defined such as a day or a month. Examples, 10 milliseconds. 2 days etc.

clocks
Chrono library defines three clocks as defined below. The configuration may vary based on platform. 

Name

Resolution

Monotonic

epoch time

time_point

system_clock➹

100 nanoseconds to 1 nanosecond

false

1970.1.1 12:00

time_point<system_clock>

steady_clock➹

1 nanosecond

true

system start time

time_point<steady_clock>

high_resolution_clock➹

1 nanosecond

true

system start time

time_point<high_resolution_clock>

All clocks define a time_point class reflecting a point since the epoch time of the clock.  They also define an API now() to return current time. Monotonic clocks are suitable for timer implementations.  The system_clock also defines two APIs to_time_t() and from_time_t() to interface with CRT time APIs. Note that high_resolution_clock  is usually an alias of either system_clock or high_resolution_clock.
This example 3, prints information about the clock.

A time_point is associated with a clock. It represents a time since epoch time of the clock. 

POSIX time functions
POSIX CRT functions are widely used for time calculations. Some of the functions use the data types discussed below. In additionenvironment time variable TZ is used for time zone settings.

Data types and structures
time_t is a 64 bit integer that represents number of milliseconds elapsed since epoch time i.e.,1970.1.1 12:00 GMT

struct timespec same as time_t but includes extra precession of time elapsed in nanoseconds.
struct timespec
{
    time_t tv_sec;  // Seconds - >= 0
    long   tv_nsec; // Nanoseconds - [0, 999999999]
};

struct tm represents a structure with breakup as shown below.
struct tm
{
    int tm_sec;   // seconds after the minute - [0, 60] including leap second
    int tm_min;   // minutes after the hour - [0, 59]
    int tm_hour;  // hours since midnight - [0, 23]
    int tm_mday;  // day of the month - [1, 31]
    int tm_mon;   // months since January - [0, 11]
    int tm_year;  // years since 1900
    int tm_wday;  // days since Sunday - [0, 6]
    int tm_yday;  // days since January 1 - [0, 365]
    int tm_isdst; // daylight savings time flag
};

Functions
NameDescription
char* asctime
(const struct tm * timeptr)
Convert time from type struct tm to character string. TZ environment is used if defined.

Example
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    //prints Sat Feb 22 19:23:46 2025
    cout << asctime (timeinfo); 
char* asctime
(const struct tm *timeptr)

Convert time from type time_t to character string as local time.

Example
    time_t rawtime;

    time (&rawtime);
    //prints Sat Feb 22 19:22:16 2025
    cout << ctime (&rawtime);
double difftime
(time_t end, time_t start);
Compute difference between two time_t  in seconds.
Example
    time_t now;
    time ( &now );

    tm tm{}; // Zero initialise 
    tm.tm_year = 2018 - 1900; // 2018
    tm.tm_mon = 9 - 1; // September
    tm.tm_mday = 21; // 21st
    tm.tm_hour = 11;
    tm.tm_min = 48;
    tm.tm_isdst = 0; // Not daylight saving

    //prints 202723807
    cout << fixed << setprecision(0) <<  difftime (now,mktime(&tm));
struct tm * gmtime
(const time_t * timer)
Convert time from type time_t to struct tm in UTC

Example
    time_t rawtime;
    struct tm * ptm;
    time ( &rawtime );
    ptm = gmtime ( &rawtime );

    //prints localtime time: 1:36
    cout << "localtime time: "  
        << (ptm->tm_hour+5)%24 << ":" << (ptm->tm_min+30)%60;
struct tm * localtime
(const time_t * timer)
Convert time from type time_t to struct tm in local time
Example
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    //prints Sat Feb 22 19:23:46 2025
    cout << asctime (timeinfo); 
time_t mktime
(struct tm * timeptr)
Convert time from struct tm to time_t as local time.

Example
    time_t now;
    time ( &now );

    tm tm{}; // Zero initialise 
    tm.tm_year = 2018 - 1900; // 2018
    tm.tm_mon = 9 - 1; // September
    tm.tm_mday = 21; // 21st
    tm.tm_hour = 11;
    tm.tm_min = 48;
    tm.tm_isdst = 0; // Not daylight saving

    //prints:6 years
    cout << fixed << setprecision(0) 
        <<  difftime (now,mktime(&tm))/(365*60*60*24.0) << " years";
size_t strftime
(char* ptr, size_t maxsize,
const char* format,const struct tm* timeptr)
Format date-and-time string for international use.

Example
    tm tm{}; // Zero initialise 
    tm.tm_year = 2018 - 1900; // 2018
    tm.tm_mon = 9 - 1; // September
    tm.tm_mday = 21; // 21st
    tm.tm_hour = 11;
    tm.tm_min = 48;
    tm.tm_wday=5;
    tm.tm_isdst = 0; // Not daylight saving
    
    char buff[100];
    strftime(buff, sizeof buff, "%c", &tm);
    //prints:Fri Sep 21 11:48:00 2018
    cout << buff <<  endl;
time_t time
(time_t* timer)
Get current system time as type time_t as local time since epoch.

Example
    time_t now;
    time ( &now );
int timespec_get
( struct timespec *ts, int base )
returns epoch time in struct timespec same as time() with extra precession.

Example
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    char buff[100];
    strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec));
    //prints:02/22/25 20:28:53 900883713
    cout <<  buff << " " << ts.tv_nsec << endl;
This example 6 demonstrates using system_clock::to_time_t(time_point) and system_clock::from_time_t(time_t)to interface with CRT.


Summary of Examples

<<
NameDescriptiongithubwandbox
ExampleRatio Librarysource    outputsource + output
Example 2Duration Arithmeticsource    outputsource + output
Example 3Clockssource    outputsource + output
Example 4time_point:usagesource    outputsource + output
Example 5time_cast:timer examplesource    outputsource + output
Example 6POSIX Time functionssource    outputsource + output


No comments:

Post a Comment