C++ 计时器:chrono库介绍

发布时间 2023-06-20 12:03:03作者: 一杯清酒邀明月

C++11有了chrono库,可以在不同系统中很容易的实现定时功能。

要使用chrono库,需要#include,其所有实现均在std::chrono namespace下。注意标准库里面的每个命名空间代表了一个独立的概念。

chrono是一个模版库,使用简单,功能强大,只需要理解三个概念:duration、time_point、clock

一 、时钟-CLOCK
chrono库定义了三种不同的时钟:

1  std::chrono::system_clock:  依据系统的当前时间 (不稳定)
2  std::chrono::steady_clock:  以统一的速率运行(不能被调整)
3  std::chrono::high_resolution_clock: 提供最高精度的计时周期(可能是steady_clock或者system_clock的typedef)

二、这三个时钟有什么区别呢?
system_clock就类似Windows系统右下角那个时钟,是系统时间。明显那个时钟是可以乱设置的。明明是早上10点,却可以设置成下午3点。

steady_clock则针对system_clock可以随意设置这个缺陷而提出来的,他表示时钟是不能设置的。

high_resolution_clock则是一个高分辨率时钟。

这三个时钟类都提供了一个静态成员函数now()用于获取当前时间,该函数的返回值是一个time_point类型,

system_clock除了now()函数外,还提供了to_time_t()静态成员函数。用于将系统时间转换成熟悉的std::time_t类型,得到了time_t类型的值,在使用ctime()函数将时间转换成字符串格式,就可以很方便地打印当前时间了。

 1 #include<iostream>
 2 #include<vector>
 3 #include<string>
 4 #include<ctime>//将时间格式的数据转换成字符串
 5 #include<chrono>
 6 using namespace std::chrono;
 7 using namespace std;
 8 int main()
 9 {
10     //获取系统的当前时间
11     auto t = system_clock::now();
12     //将获取的时间转换成time_t类型
13     auto tNow = system_clock::to_time_t(t);
14 
15     //ctime()函数将time_t类型的时间转化成字符串格式,这个字符串自带换行符
16     string str_time = std::ctime(&tNow);
17 
18     cout<<str_time;
19 
20     return 0;
21 }

三、持续的时间 - duration
td::chrono::duration<int,ratio<60,1>> ,表示持续的一段时间,这段时间的单位是由ratio<60,1>决定的,int表示这段时间的值的类型,函数返回的类型还是一个时间段duration

std::chrono::duration<double,ratio<60,1>>

由于各种时间段(duration)表示不同,chrono库提供了duration_cast类型转换函数。

duration_cast用于将duration进行转换成另一个类型的duration。

duration还有一个成员函数count(),用来表示这一段时间的长度

 1 #include<iostream>
 2 #include<string.h>
 3 #include<chrono>
 4 using namespace std::chrono;
 5 using namespace std;
 6 int main()
 7 {
 8     auto start = std::chrono::steady_clock::now();
 9     for(int i=0;i<100;i++)
10         cout<<"nice"<<endl;
11     auto end = std::chrono::steady_clock::now();
12 
13     auto tt = std::chrono::duration_cast<microseconds>(end - start);
14 
15     cout<<"程序用时="<<tt.count()<<"微秒"<<endl;
16     return 0;
17 }

四、时间点 - time_point
std::chrono::time_point 表示一个具体时间,如上个世纪80年代、你的生日、今天下午、火车出发时间等,只要它能用计算机时钟表示。鉴于我们使用时间的情景不同,这个time point具体到什么程度,由选用的单位决定。一个time point必须有一个clock计时

设置一个时间点:

std::time_point<clock类型> 时间点名字

1 //设置一个高精度时间点
2     std::time_point<high_resolution_clock> high_resolution_clock::now();
1 //设置系统时钟
2     std::chrono::time_point<std::chrono::system_clock> now=std::chrono::system_clock::now();

另一个实例:

  1 #define _CRT_SECURE_NO_WARNINGS //localtime()需要这个宏
  2 #include<iostream>
  3 #include<chrono>
  4 #include<vector>
  5 #include<string>
  6 #include<algorithm>
  7 //#include<stdio.h>
  8 
  9 #include<iomanip> //put_time需要的头文件
 10 
 11 #include<sstream>
 12 
 13     // template <class _Rep>
 14     // struct treat_as_floating_point : is_floating_point<_Rep> {}; // tests for floating-point type
 15 
 16     // template <class _Rep>
 17     // _INLINE_VAR constexpr bool treat_as_floating_point_v = treat_as_floating_point<_Rep>::value;
 18 
 19     // // STRUCT TEMPLATE duration_values
 20     // template <class _Rep>
 21     // struct duration_values { // gets arithmetic properties of a type
 22     //     _NODISCARD static constexpr _Rep zero() noexcept {
 23     //         // get zero value
 24     //         return _Rep(0);
 25     //     }
 26 
 27     //     _NODISCARD static constexpr _Rep(min)() noexcept {
 28     //         // get smallest value
 29     //         return numeric_limits<_Rep>::lowest();
 30     //     }
 31 
 32     //     _NODISCARD static constexpr _Rep(max)() noexcept {
 33     //         // get largest value
 34     //         return (numeric_limits<_Rep>::max)();
 35     //     }
 36     // };
 37 
 38 //时间长度
 39 void Func1(){
 40     //chrono重载了各种运算符
 41     std::chrono::hours             c1(1);                //1小时
 42     std::chrono::minutes           c2(60);               //60分钟
 43     std::chrono::seconds           c3(60*60);            //60*60s
 44     std::chrono::milliseconds      c4(60*60*1000);       //60*60*1000毫秒
 45     std::chrono::microseconds      c5(60*60*1000*1000);  //微秒 溢出
 46     std::chrono::nanoseconds       c6(60*1000*1000*1000);//纳秒 溢出
 47 
 48     if(c1==c2){
 49         std::cout<<"c1==c2"<<std::endl;
 50     }
 51     if(c1==c3){
 52         std::cout<<"c1==c3"<<std::endl;
 53     }
 54     if(c2==c3){
 55         std::cout<<"c2==c3"<<std::endl;
 56     }
 57 
 58     //获取时钟周期的值,返回的是int整数
 59     std::cout<<"c1= "<<c1.count()<<std::endl;
 60     std::cout<<"c2= "<<c2.count()<<std::endl;
 61     std::cout<<"c3= "<<c3.count()<<std::endl;
 62     std::cout<<"c4= "<<c4.count()<<std::endl;
 63 
 64     std::chrono::seconds             c7(1);               //1秒
 65     std::chrono::milliseconds        c8(1*1000);          //1000毫秒;1s
 66     std::chrono::microseconds        c9(1*1000*1000);     //1000*1000微秒 1s
 67     std::chrono::nanoseconds         c10(1*1000*1000*1000);//1000*1000*1000纳秒 1s;
 68 
 69     std::cout<<c7.count()<<std::endl;
 70     std::cout<<c8.count()<<std::endl;
 71     std::cout<<c9.count()<<std::endl;
 72     std::cout<<c10.count()<<std::endl;
 73 }
 74 
 75 //系统时间
 76 /**
 77  * @brief 
 78  * 
 79  * system_clock 类支持了对系统时钟的访问, 提供了三个静态成员函数:
 80 返回当前时间的时间点。
 81 static std::chrono::time_point<std::chrono::system_clock> now() noexcept;
 82 将时间点 time_point 类型转换为 std::time_t 类型。
 83 static std::time_t to_time_t( const time_point& t ) noexcept;
 84 将 std::time_t 类型转换为时间点 time_point 类型。
 85 static std::chrono::system_clock::time_point from_time_t( std::time_t t ) noexcept;
 86  */
 87 
 88 void Func2(){
 89     //静态成员函数 static std::chrono::time_point<std::chrono::system_clock> now() noexcept
 90     //这些都可以简写用auto now=std::chrono::system_clock()::now()接收
 91     //1、静态成员函数 static std::chrono::system_clock::now()用来获取系统时间,C++时间
 92     std::chrono::time_point<std::chrono::system_clock> now=std::chrono::system_clock::now();
 93 
 94     //2、静态成员函数 static std::chrono::system_clock::to_time_t()把C++系统时间转换为time_t (utc时间)
 95     time_t t_now=std::chrono::system_clock::to_time_t(now);
 96 
 97     //3、std::localtime()函数把time_t时间转换为本地时间(北京时间)
 98     // std::localtime()不是线程安全的,VS用localtime_t()代替,linux用local_time_r()代替
 99     //tm结构体
100     tm* tm_now=localtime(&t_now);
101 
102     //格式化输出tm结构体中的成员
103     std::cout<<std::put_time(tm_now,"%Y-%m-%d %H:%M:%S")<<std::endl;
104     std::cout<<std::put_time(tm_now,"%Y-%m-%d")<<std::endl;
105     std::cout<<std::put_time(tm_now,"%H:%M:%S")<<std::endl;
106 
107     //但是通常C++一般不打印出时间,而是把时间存储到一个字符串中
108 
109     std::stringstream ss;  //创建stringstream对象 ss,需要包含<sstream>头文件
110     ss<<std::put_time(tm_now,"%Y-%m-%d %H:%M:%S");
111     std::string time_str=ss.str();
112     std::cout<<time_str<<std::endl;
113 }   
114 
115 // struct steady_clock { // wraps QueryPerformanceCounter
116 //         using rep                       = long long;
117 //         using period                    = nano;
118 //         using duration                  = nanoseconds;
119 //         using time_point                = chrono::time_point<steady_clock>;
120 //         static constexpr bool is_steady = true;
121 
122 //         _NODISCARD static time_point now() noexcept { // get current time
123 //             const long long _Freq = _Query_perf_frequency(); // doesn't change after system boot
124 //             const long long _Ctr  = _Query_perf_counter();
125 //             static_assert(period::num == 1, "This assumes period::num == 1.");
126 //             // Instead of just having "(_Ctr * period::den) / _Freq",
127 //             // the algorithm below prevents overflow when _Ctr is sufficiently large.
128 //             // It assumes that _Freq * period::den does not overflow, which is currently true for nano period.
129 //             // It is not realistic for _Ctr to accumulate to large values from zero with this assumption,
130 //             // but the initial value of _Ctr could be large.
131 //             const long long _Whole = (_Ctr / _Freq) * period::den;
132 //             const long long _Part  = (_Ctr % _Freq) * period::den / _Freq;
133 //             return time_point(duration(_Whole + _Part));
134 //         }
135 //     };
136 
137 //     using high_resolution_clock = steady_clock;
138 // } // namespace chrono
139 
140 //计时器 steady_clock 类相当于秒表,操作系统只要启动就会进行时间的累加,常用于耗时的统计(精确到纳秒) 。
141 void Func3(){
142     //静态成员函数std::chrono::steady_clock::now()获取时间的开始点
143     std::chrono::time_point<std::chrono::steady_clock> start=std::chrono::steady_clock::now();
144     //auto start=std::chrono::steady_clock::now();
145     //执行一些代码,消耗时间
146     std::vector<std::string> vec1{"banana","apple","pear"};
147     std::for_each(vec1.begin(),vec1.end(),[&vec1](std::string str){
148         std::cout<<str<<" ";
149     });
150     std::cout<<std::endl;
151     //静态成员函数std::chrono::steady_clock::now()获取时间的结束点
152     auto end=std::chrono::steady_clock::now();
153 
154     //计算消耗的时间,单位是纳秒
155     auto dt=end-start;
156     std::cout<<"耗时: "<<dt.count()<<"纳秒 ("<<(double)dt.count()/(1000*1000*1000)<<"秒) "<<std::endl;
157 
158 }
159 
160 int main(int argc,char* argv[]){
161     Func1();
162     Func2();
163     Func3();
164     return 0;
165 }

输出结果:

 1 PS D:\时间操作 chrono 库\bin\Debug> .\main.exe
 2 c1==c2
 3 c1==c3
 4 c2==c3
 5 c1= 1
 6 c2= 60
 7 c3= 3600
 8 c4= 3600000
 9 1
10 1000
11 1000000
12 1000000000
13 2023-01-04 22:32:43
14 2023-01-04
15 22:32:43
16 2023-01-04 22:32:43
17 banana apple pear
18 耗时: 733400纳秒 (0.0007334秒)
19 PS D:\时间操作 chrono 库\bin\Debug>