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:
system_clock (C++11): wall clock time from the system-wide realtime clock
steady_clock (C++11): monotonic clock that will never be adjusted
high_resolution_clock (C++11): the clock with the shortest tick period available
utc_clock (C++20): Clock for Coordinated Universal Time (UTC)
tai_clock (C++20): Clock for International Atomic Time (TAI)
gps_clock (C++20): Clock for GPS time
file_clock (C++20): Clock used for file time
local_t (C++20): pseudo-clock representing local time
C++ also inherits the C clock function, which returns the approximate processor time used by the process
since the beginning of an implementation-defined era related to the program's execution.
To convert result value to seconds divide it by CLOCKS_PER_SEC. The clock function:
The only method specified in the standard to measure CPU time
It's up to the user to keep track of the duration unit
// Same as using hoursconstexprintseconds_per_hour=60*60;std::chrono::duration<int,std::ratio<seconds_per_hour>>hours_as_int;hours_as_int=std::chrono::duration_cast<std::chrono::duration<int,std::ratio<60*60>>>(seconds_as_double);std::cout<<"hours_as_int.count() : "<<hours_as_int.count()<<" hours"<<'\n';
std::chrono::duration<int,std::ratio<seconds_per_hour>>hours_as_int3;// same as using std::hourshours_as_int3=std::chrono::duration_cast<std::chrono::duration<int,std::ratio<seconds_per_hour>>>(seconds_as_double_3);std::cout<<"hours_as_int3.count() : "<<hours_as_int3.count()<<" hours"<<'\n';
1 2 3 4 5 6 7 8 9101112131415161718192021222324
// While std::std::chrono::parse is not available in all main compilersautohours=std::chrono::duration_cast<std::chrono::hours>(d3);if(hours.count()>0){std::cout<<hours.count()<<" hours";}d3-=hours;autoseconds=std::chrono::duration_cast<std::chrono::seconds>(d3);if(seconds.count()>0){std::cout<<seconds.count()<<" seconds";}d3-=seconds;automilliseconds=std::chrono::duration_cast<std::chrono::milliseconds>(d3);if(milliseconds.count()>0){std::cout<<milliseconds.count()<<" milliseconds";}d3-=milliseconds;autonanoseconds=std::chrono::duration_cast<std::chrono::nanoseconds>(d3);if(nanoseconds.count()>0){std::cout<<nanoseconds.count()<<" nanoseconds";}