Chrono Time object in C++11

Source: Internet
Author: User
Tags add time

Before c++11, there was always a problem with how to get high-precision time, and different platforms needed to be obtained in different ways. Now C++11 provides the Chrono. This is one that can solve all the need for time.


Three concepts are presented in Chrono:

durations: represents a time interval that can be used in different time units, such as hours, days, and smallest to nanoseconds. You can also customize a special time interval.

Time points: save a point in a moment. such as the current time, tomorrow's this time, wife's birthday. Wait a minute.. Precision can reach nanoseconds, or custom precision.

clocks: A clock that can be converted to and from time points. The c++11 defines three clocks:

System_clock: Provides the same clock as the current system time, and each call to System_clock::now () will get the current time of the system.

Steady_clock: Describes the increment of a time at which the clock never decreases, and the time taken with Steady_clock::now () will not be affected by system_clock due to changes in system time. However, it is not possible to get the current time value from Steady_clock because it is just an increment of the current system. The best example of using it is using it to get the execution time of a piece of code.

High_resolution_clock: A high-precision clock, generally equal to one of the two clocks above.


Chrono also provides two methods for converting between duartions and time_points in different units:

Time_porint_cast: Used to convert two different accuracy of the time_points, if the accuracy is not enough, will discard the latter several.

duration_cast: Used to convert two different accuracy of the duration, if the accuracy is not enough, will discard the latter several.


Here are a few examples:

1. Let the program suspend for a period of time:

#include <chrono> #include <iostream>using namespace std::chrono;using namespace Std;int main () {Auto T = Steady_clock::now ();d o{} while (Steady_clock::now () < T + milliseconds () cout << "This is empty 41 milliseconds"; return 0;}

Note the above milliseconds (41), which is a duartions<long long,milli> type, also in Chrono when it is defined. If the machine is good enough, you can also use Nanosecond (nanoseconds).


2. How much time is used for testing


#include <chrono> #include <iostream> #include <ratio>using namespace std::chrono;using namespace std ; int main () {Auto up = Steady_clock::now ();d osome (), Auto down = Steady_clock::now (); Auto d = duration_cast< Microseconds> (down-up);//auto d = duration_cast<duration<double,micro>> (down-up);p rintf ("Spents:%f microseconds Over! ", D.count ()); return 0;}

This code can show how much time is used by your Dosome () method. A microsecond-level count is given. The above microseconds is a microsecond long integer, try to use the commented out code to try, will give a microsecond of 1 decimal display.


3, this example shows how to set the time interval of the unit and time of operation.

#include <chrono> #include <iostream>using namespace std::chrono;using namespace Std;int main () {// Set a unit for the time interval of one day duration<int,ratio<60*60*24>> one_day (1); System_clock::time_point today = System_clock:: Now (); System_clock::time_point tomorrow = today + one_day;time_t Tt;tt = system_clock::to_time_t (today); cout << " Today is: "<< CTime (&TT); TT = system_clock::to_time_t (tomorrow); cout <<" Tomorrow'll be: "<< CTI Me (&TT); return 0;}

The above example defines a time interval one_day, using ratio as the proportional unit. Then get the current system time. Use the current time to add time intervals, which equals the time of tomorrow.


4, a very simple log function implementation

Log.cpp:

#include   "log.h" #include  <iostream> #include  <chrono>using namespace std:: chrono;static file *file = nullptr;static int _level = 10;static  Steady_clock::time_point startup = steady_clock::now (); Tm millijs (const long  LONG&NBSP;T) {  tm tt ;  long long tmp = t / 1000;     tt.tm_sec = tmp % 60;  tmp /= 60;     tt.tm_min = tmp % 60;  tmp /= 60;     Tt.tm_hour = tmp % 24;  tmp /= 24;    tt.tm_mday  =  (int) Tmp;    return tt;} Int _log (int const level,const char *msg) {  //Opens a file with the current year/month/day as the filename. Additional content.   if (!file) {    time_t curtime = system_clock::to_time_t (System_clock::now ());     tm t = *localtime ( &curtime)       char s[sizeof (_dir)/sizeof (_dir[0])  + 20];     sprintf (s,  "%s%04d%02d%02d.log", _dir,t.tm_year+1900,t.tm_mon+1,t.tm_mday);     file = fopen (s,  "a")   ;  }  if (level <=  _level) {    auto now = steady_clock::now ();     Auto d = duration_cast<milliseconds> (now - startup);     tm  notime = millijs (D.count ());         fprintf (file, "%d_ %02d:%02d:%02d.%d lev:%d:%s\n ", notime.tm_mday,notime.tm_hour,notime.tm_min,notime.tm_sec, (int) d.count () &NBSP;%&NBSP;1000,LEVEL,MSG);           return 1;   }    return 0;} 

Log.h

#ifndef __test__log__#define __test__log__#define NOLOG 0#endif/* defined (__test__log__) *///will record a log, level represents the rank of this log, Log is logged only if the log level is set higher than the rank parameter, otherwise the log is not logged. If the NOLOG definition does not produce a log//return 0 for the file not written int _log (int level,const char *msg);//Specify the location of the directory address static const char *_dir = "log/"; #if nolog# Define log (Level,msg) #else # define log (level,msg) _log (level,msg) #endif

The above example simply implements a logging function, which must be added to the log folder under the application directory for normal logging. The log file is not considered too large because the log file is always open. If used in multiple threads, strange records may appear.

The example uses system_clock::to_time_t () to convert to a familiar time_t structure.

Statement:static steady_clock::time_point startup = steady_ Clock:now (); Gets the current increment of the program runtime, which is the base value, and each record records the length of time the program is running.

method Millijs () Converts a time interval value directly to a length of time, showing whether a value is actually used throughout the structure to represent time data that is relative to a time record. In this program, the time is relative to the moment the program is started. In this program, no matter how you modify the system time, it will correctly log the program run duration.


Ps:system_clock has a to_time_t method, and Steardy_clock does not have this method. Although it makes no sense, it is necessary to take its value, Steardy_clcok::now () can be used to turn out the Time_porint Time_since_epoch() method. The above example translates to the required time value.



Summary: C++11 's Chrono can do anything we need time to do. Some people say that c++11 is like a new programming language. I am now beginning to accept this sentence very much!


Reference: http://www.cplusplus.com/reference/chrono/


This article is from the "Chalet" blog, please be sure to keep this source http://udbjqr.blog.51cto.com/10492244/1688419

Chrono Time object in C++11

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.