
std::chrono::duration
template< class Rep, | (since C++11) |
Class template represents a time interval.
It consists of a count of ticks of type and a tick period, where the tick period is a compile-time rational representing the time in seconds from one tick to the next.
The only data stored in a is a tick count of type . If is floating point, then the can represent fractions of ticks. is included as part of the duration's type, and is only used when converting between different durations.
[edit]Member types
Member type | Definition |
, an arithmetic type representing the number of ticks | |
(until C++17)(since C++17), a std::ratio representing the tick period (i.e. the number of second's fractions per tick) |
[edit]Member functions
[edit]Non-member functions
[edit]Helper types
Type | Definition |
std::chrono::nanoseconds | duration</*signed integer type of at least 64 bits*/, std::nano> |
std::chrono::microseconds | duration</*signed integer type of at least 55 bits*/, std::micro> |
std::chrono::milliseconds | duration</*signed integer type of at least 45 bits*/, std::milli> |
std::chrono::seconds | duration</*signed integer type of at least 35 bits*/> |
std::chrono::minutes | duration</*signed integer type of at least 29 bits*/, std::ratio<60>> |
std::chrono::hours | duration</*signed integer type of at least 23 bits*/, std::ratio<3600>> |
std::chrono::days(since C++20) | duration</*signed integer type of at least 25 bits*/, std::ratio<86400>> |
std::chrono::weeks(since C++20) | duration</*signed integer type of at least 22 bits*/, std::ratio<604800>> |
std::chrono::months(since C++20) | duration</*signed integer type of at least 20 bits*/, std::ratio<2629746>> |
std::chrono::years(since C++20) | duration</*signed integer type of at least 17 bits*/, std::ratio<31556952>> |
Note: each of the predefined duration types up to covers a range of at least ±292 years.
Each of the predefined duration types , , and covers a range of at least ±40000 years. is equal to 365.2425 (the average length of a Gregorian year). is equal to 30.436875 (exactly 1/12 of ). | (since C++20) |
[edit]Helper classes
[edit]Literals
Note: the literal suffixes and do not refer to and but to and , respectively. | (since C++20) |
[edit]Notes
The actual time interval (in seconds) that is held by a duration object is roughly equal to d.count()* D::period::num/ D::period::den, where is of type and is an object of such type.
[edit]Example
This example shows how to define several custom duration types and convert between types:
Run this code
Output:
1. Time Points
In this article, we will learn about chrono library in C++. This library is used for managing date and time. As timer are different for different systems, so to bring precision we can use this library. The chrono library is also used to measure time elapsed during execution of a C++ program. It can measure the time in seconds, milli seconds , micro seconds and nano seconds.
Durations are the heart of the library.
These six durations represent the convenient highlevel access:
- hours
- minutes
- seconds
- milliseconds
- microseconds
- nanoseconds
Good thing about this library is that it provides accurracy irrespective of machines.
Now lets consider about C++20 becomes much easier to work with
because you can easily print values out, even without
knowing their type.
Output:
Chrono Library defines mainly 3 types of utilities/functions:-
- Time Points
- Clocks
- Durations
These are implemented by using specific time reference and calculating.Internally, the object stores an object of a duration type, and uses the Clock type as a reference for its (starting point)epoch.
Here let's see the template:
So, we can that time_point is a wrapper around a duration.
These represent Same value and same representation but just a different
meaning.The time_point gives subset of arithmetic algebra so that we can catch logic errors at compile-time.
Example given below:
So, we can that in simple words that the time_point is templated can detect errors of mising time points from various available clocks
Example given below:
A clock defines an epoch and a tick period. For example, a clock might tick in milliseconds since the UNIX epoch (January 1, 1970) or tick in nanoseconds since the start of the program. In addition, a clock provides a type for any timepoint specified according to this clock.
SO, the interface of a clock provides a function now() to yield an object for the current point in
time.
i. system_clock :- It will show the current time of system.
ii.steady_clock :- Its a clock that can never be adjusted . It keeps on going.
iii. high_resolution_clock :- To increase the resolution i.e to avail samllest tick that would be possible.
Example of Count ticks:-
The duration shows a duration/step of time, and can come in any unit.
It measures the time spans, like: one hour, two minutes, or five milliseconds.
Now let's see the template :
These Durations are represented by arithmetic type, else by a class type representing the arithmetic type.
• int, long, double, safe , etc.
• duration::period is a compile-time fraction representing the time in seconds between each integral value stored in the duration.
- defines several convenience type aliases for common units.
Existing Units
- nanoseconds
- microseconds
- milliseconds
- seconds
- minutes
- hours
New in c++20
Now lets see the difference between time point and date:
- The Time points can be taken to have arbitrarily fine precision.
- The Time points can be taken to have arbitrarily coarse precision
- And When the time point has a precision of a day, we call it a date.
- All the precisions has a type in the chrono system.
Just take a look above for the difference.
In simple words , the calendar is a collection of dates, where each date will be having a unique name.
When we have different calenders then Different calendars can refer to the same physical date, but have different names for that date.
sys_days is the canonical calendar in
Let's start with The civil calender :
This represents the last day of the {year, month} pair.
- Constructible from a year and month.
- Implicitly convertible to sys_days (it's a partial calendar).
- Has year and month and day getters.
- Equality and less-than comparable.
- Does year and month-oriented arithmetic.
So , the Constructible with conventional syntax operators by replacing the day-specifier with last.
- This is also Implicitly convertible to year_month_day.
Time-points can be displayed in various specific time-zones.
Due to the extended chrono library, the following use-cases are easy to implement:
Now we can represent the dates in various forms:
get the last day of a month
get the number of days between two dates
printing the current time in various time-zones
Chrono Library is not only a header , its also a namespace. All elements in Chrono header (except for the common_type specializations) are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace.
C++ Example Code :
OUTPUT OF CODE :
Example 2:
Output Of Code :
With this article at OpenGenus, you must have got a complete idea of chrono library in C++ to handle time related data. Enjoy.
<chrono>
header
Time library
is the name of a header, but also of a sub-namespace: All the elements in this header (except for the common_type specializations) are not defined directly under the namespace (like most of the standard library) but under the namespace.The elements in this header deal with time. This is done mainly by means of three concepts:
- Durations
- They measure time spans, like: one minute, two hours, or ten milliseconds.
In this library, they are represented with objects of the duration class template, that couples a count representation and a period precision (e.g., ten milliseconds has ten as count representation and milliseconds as period precision). - Time points
- A reference to a specific point in time, like one's birthday, today's dawn, or when the next train passes.
In this library, objects of the time_point class template express this by using a duration relative to an epoch (which is a fixed point in time common to all time_point objects using the same clock). - Clocks
- A framework that relates a time point to real physical time.
The library provides at least three clocks that provide means to express the current time as a time_point: system_clock, steady_clock and high_resolution_clock.
For typical examples, see steady_clock or system_clock.
Classes
and :
- duration
- Duration (class template)
- time_point
- Time point (class template)
clocks:
- system_clock
- System clock (class)
- steady_clock
- Steady clock (class)
- high_resolution_clock
- High resolution clock (class)
traits:
- treat_as_floating_point
- Treat as floating point (class template)
- duration_values
- Duration values (class template)
- common_type (duration)
- Specialization of common_type for duration (class template)
Functions
- duration_cast
- Duration cast (function template)
- time_point_cast
- Time_point cast (function template)
Class instantiation typedefs
The following convenience typedefs of instantiations of are also defined in this namespace:- hours
- Duration in hours (class)
- minutes
- Duration in minutes (class)
- seconds
- Duration in seconds (class)
- milliseconds
- Duration in milliseconds (class)
- microseconds
- Duration in microseconds (class)
- nanoseconds
- Duration in nanoseconds (class)
Chrono in C++
Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision. The unique thing about chrono is that it provides a precision-neutral concept by separating duration and point of time (“timepoint”) from specific clocks.
chrono is the name of a header and also of a sub-namespace: All the elements in this header (except for the common_type specializations) are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace.
The elements in this header deal with time. This is done mainly by means of three concepts:
Duration
A duration object expresses a time span by means of a count like a minute, two hours, or ten milliseconds. For example, “42 seconds” could be represented by a duration consisting of 42 ticks of a 1-second time unit.
|
Output:
duration (in periods): 60000 milliseconds. duration (in seconds): 60 seconds.
Clock
A clock consists of a starting point (or epoch) and a tick rate. For example, a clock may have an epoch of February 22, 1996 and tick every second. C++ defines three clock types:
- system_clock-It is the current time according to the system (regular clock which we see on the toolbar of the computer). It is written as- std::chrono::system_clock
- steady_clock-It is a monotonic clock that will never be adjusted.It goes at a uniform rate. It is written as- std::chrono::steady_clock
- high_resolution_clock– It provides the smallest possible tick period. It is written as-std::chrono::high_resolution_clock
Time point
A time_point object expresses a point in time relative to a clock’s epoch. Internally, the object stores an object of a duration type, and uses the Clock type as a reference for its epoch.
|
Output:
f(42) = 267914296 finished computation at Wed Jan 4 05:13:48 2017 elapsed time: 2.14538sThis article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Coursefor Basic to Advanced C++ and C++ STL Course for foundation plus STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Example c chrono
#include <iostream>
#include <chrono>
#include <unistd.h>
usingnamespacestd;
// Main function to measure elapsed time of a C++ program
// using Chrono library
intmain()
{
auto start=chrono::steady_clock::now();
// do some stuff here
sleep(3);
auto end=chrono::steady_clock::now();
cout<<"Elapsed time in nanoseconds: "
<<chrono::duration_cast<chrono::nanoseconds>(end-start).count()
<<" ns"<<endl;
cout<<"Elapsed time in microseconds: "
<<chrono::duration_cast<chrono::microseconds>(end-start).count()
<<" µs"<<endl;
cout<<"Elapsed time in milliseconds: "
<<chrono::duration_cast<chrono::milliseconds>(end-start).count()
<<" ms"<<endl;
cout<<"Elapsed time in seconds: "
<<chrono::duration_cast<chrono::seconds>(end-start).count()
<<" sec";
return0;
}
Date and time utilities
C++ includes support for two types of time manipulation:
- The library, a flexible collection of types that track time with varying degrees of precision (e.g. std::chrono::time_point).
- C-style date and time library (e.g. std::time)
[edit] library
The library defines three main types as well as utility functions and common typedefs.
- clocks
- time points
- durations
[edit]Clocks
A clock consists of a starting point (or epoch) and a tick rate. For example, a clock may have an epoch of January 1, 1970 and tick every second. C++ defines several clock types:
[edit]Time point
A time point is a duration of time that has passed since the epoch of a specific clock.
[edit]Duration
A duration consists of a span of time, defined as some number of ticks of some time unit. For example, "42 seconds" could be represented by a duration consisting of 42 ticks of a 1-second time unit.
[edit]Time of day
splits a duration representing time elapsed since midnight into hours, minutes, seconds, and fractional seconds, as applicable. It is primarily a formatting tool.
[edit]Calendar
[edit]Time zone
[edit] I/O
[edit]C-style date and time library
Also provided are the C-style date and time functions, such as std::time_t, std::difftime, and CLOCKS_PER_SEC.
[edit]Example
This example displays information about the execution time of a function call:
Run this code
Possible output:
Similar news:
- Kelley blue book cadillac cts
- Above the mist wedding packages
- Walmart true availability form pdf
- Does shades eq cover gray
- Ps4 controller light bar mod
- Does moviepass work in canada
- Snake draft picks 10 team
- At&t now remote
- Alkaline water mill near me
- Class d home theater amplifier
- 2 bedroom apartment in dubai
Include the standard header to define classes and functions that represent and manipulate time durations and time instants.
Beginning in Visual Studio 2015, the implementation of has changed to meet the C++ Standard requirements for steadiness and monotonicity:
- is now based on
- is now a typedef for In the Microsoft C++ implementation, is now a for . However, this isn't necessarily the case for other implementations.
Requirements
Header:
Namespace:
Calendrical types
Name | Description |
---|---|
struct | Describes specializations of class template for instantiations of and . |
class | A day of the month. For example, the 25th day of the month. |
class | A time interval. |
struct | Provides specific values for the template parameter . |
class | Splits a into hours:minutes:seconds. |
Used to indicate the last item in a month such as last day of the week of a month (the last Tuesday of February 2020) or the last day of a month (the last day of April 2019). | |
class | A date and a value for an inserted leap second. |
struct | The data returned by . |
class | A month of a year. For example, July. |
class | A specific day of a specific month. For example, July 30. |
class | The last day of a month. |
class | The nth weekday of a specific month. |
class | The nth weekday of a specific month. |
class | A point in time. |
class | A day of the week. |
class | The last weekday of a month. |
class | Combines a day of the week with an index that represents the weekday of the month. |
class | A year in the Gregorian calendar. |
class | A year and month. The day isn't specified. |
class | A year, month, and day. |
class | The last day of a specific month and year. |
class | A specific year, month, and nth weekday of the month. |
class | A specific year, month, and last weekday of the month. |
Clocks
Name | Description |
---|---|
class | An alias for the clock used for , which is used to express file timestamps. |
class | A clock that keeps GPS time. Measures time starting from the first Sunday of January 1980 at 00:00:00 UTC. |
struct | A clock with a nanosecond tick period. |
struct | A pseudo-clock used as an argument to the template to indicate that the represents local time. |
struct | A clock. This clock is preferred for measuring time intervals. |
struct | A clock based on the real-time clock of the system. |
class | Measures International Atomic Time (TAI) starting from Thursday, January 1, 1958 at 00:00:00. This clock doesn't account for leap seconds. |
class | Measures time since 00:00:00 UTC on Thursday, January 1, 1970. This clock accounts for leap seconds, and is the time standard used around the world. |
Time zones
Name | Description |
---|---|
An enum that specifies how to resolve the ambiguous conversion of a to a . | |
Provides a low-level interface to time zone information about the result of converting a to a . | |
Provides a low-level interface to time zone information about the result of converting a to a . | |
class | All time zone transitions for a specific geographic area. |
class | An alternative name for a . |
struct | Represents a copy of the time zone database. |
class | A singleton list of time zone databases. |
class | A pairing of a and a with a specified precision. |
struct | Used to associate a different default time zone with a , and optionally map a custom name to that default time zone. |
Exceptions
Name | Description |
---|---|
Error thrown when a is converted to a and the result is ambiguous. | |
Error thrown when a is converted to a and the result is a time that doesn't exist. |
Functions
Time zone related
Operators
Name | Description |
---|---|
Subtract or negate various objects. | |
Inequality operator that is used with various objects. | |
Operator for modulo operations on objects. | |
Multiplication operator for objects. | |
Division operator for objects. | |
Provides syntax to create calendar dates. | |
Add to various objects. | |
Determines whether various objects are less than another. | |
Determines whether various objects are less than or equal to another. | |
Determines whether various objects are equal to each other. | |
Determines whether various objects are greater than another. | |
Determines whether various objects are greater than or equal to another. |
Typedefs
For more information about ratio types that are used in the following typedefs, see .
Convenience types
Name | Description |
---|---|
Synonym for a type that has a tick period of one billionth (1/1,000,000,000) of a second. | |
Synonym for a type that has a tick period of one-millionth (1/1,000,000) of a second. | |
Synonym for a type that has a tick period of one-thousandth (1/1,000) of a second. | |
Synonym for a type that has a tick period of 1 second. | |
Synonym for a type that has a tick period of 1 minute. | |
Synonym for a type that has a tick period of 1 hour. |
Convenience types
Name | Description |
---|---|
A synonym for . Represents a for a . You specify the , for example, . | |
A synonym for A count of seconds, represented by a that is associated with a . | |
A synonym for . Represents a for a . You specify the , for example, . | |
A synonym for . A count of days, represented by a that isn't associated with any time zone. | |
A synonym for . | |
A synonym for . Represents a for a local time that isn't associated with a time zone yet. You specify the , for example, . A is a local time somewhere. It isn't the current local time of your computer's clock. Only when you pair a with a do you get a point in time that can be converted to UTC time, or the time in a specific time zone. | |
A synonym for . A count of days since the system_clock's epoch, represented by a that is associated with a . | |
A synonym for . A count of non-leap seconds since the epoch of (Jan 1, 1970 00:00:00 UTC), represented by a that is associated with a . | |
A synonym for . You specify the , for example, . Represents a returned from . It represents Unix time, which closely approximates UTC time. | |
A synonym for . A count of seconds, represented by a that is associated with a . | |
A synonym for . You provide the , for example, . Represents a for a . | |
A synonym for | |
A synonym for . You provide the , for example, . Represents a for a . |
Type traits
Literals
(C++11) The header defines the following user-defined literals that you can use for greater convenience, type-safety, and maintainability of your code. These literals are defined in the inline namespace and are in scope when is in scope.
Declaration | Description |
---|---|
Specifies hours as an integral value. | |
Specifies hours as a floating-point value. | |
Specifies minutes as an integral value. | |
Specifies minutes as a floating-point value. | |
Specifies minutes as an integral value. | |
Specifies seconds as a floating-point value. | |
Specifies milliseconds as an integral value. | |
Specifies milliseconds as a floating-point value. | |
Specifies microseconds as an integral value. | |
Specifies microseconds as a floating-point value. | |
Specifies nanoseconds as an integral value. | |
Specifies nanoseconds as a floating-point value. |
The following examples show how to use literals:
See also
Header Files Reference
Feedback
View all page feedback