标签:值类型 minutes std clu 第一个 标准 记录 代码 lap
1 typedef duration <Rep, ratio<3600,1>> hours;
2 typedef duration <Rep, ratio<60,1>> minutes;
3 typedef duration <Rep, ratio<1,1>> seconds;
4 typedef duration <Rep, ratio<1,1000>> milliseconds;
5 typedef duration <Rep, ratio<1,1000000>> microseconds;
6 typedef duration <Rep, ratio<1,1000000000>> nanoseconds;
通过定义这些常用的时间间隔类型,我们能方便的使用它们,比如线程的休眠:
1 std::this_thread::sleep_for(std::chrono::seconds(3)); //休眠三秒
2 std::this_thread::sleep_for(std::chrono:: milliseconds (100)); //休眠100毫秒
1 <span style="font-size:14px;color:#333333;">#include <iostream>
2 #include <ratio>
3 #include <chrono>
4 int main ()
5 {
6 using namespace std::chrono;
7 typedef duration<int,std::ratio<60*60*24>> days_type;
8 time_point<system_clock,days_type> today = time_point_cast<days_type>(system_clock::now());
9 std::cout << today.time_since_epoch().count() << " days since epoch" << std::endl;
10 return 0;
11 }</span>
1 #include <iostream>
2 #include <chrono>
3 int main()
4 {
5 std::chrono::steady_clock::time_point t1 = std::chrono::system_clock::now();
6 std::cout << "Hello World\n";
7 std::chrono::steady_clock::time_point t2 = std::chrono:: system_clock::now();
8 std::cout << (t2-t1).count()<<” tick count”<<endl;
9 }
system_clock的to_time_t方法可以将一个time_point转换为ctime,而from_time_t方法则是相反的,它将ctime转换为time_point:
1 #include<chrono> 2 usingnamespace std; 3 usingnamespace std::chrono; 4 classTimer 5 { 6 public: 7 Timer() : m_begin(high_resolution_clock::now()) {} 8 void reset() { m_begin = high_resolution_clock::now(); } 9 //默认输出毫秒 10 int64_t elapsed() const 11 { 12 return duration_cast<chrono::milliseconds>(high_resolution_clock::now() - m_begin).count(); 13 } 14 //微秒 15 int64_t elapsed_micro() const 16 { 17 return duration_cast<chrono::microseconds>(high_resolution_clock::now() - m_begin).count(); 18 } 19 //纳秒 20 int64_t elapsed_nano() const 21 { 22 return duration_cast<chrono::nanoseconds>(high_resolution_clock::now() - m_begin).count(); 23 } 24 //秒 25 int64_t elapsed_seconds() const 26 { 27 return duration_cast<chrono::seconds>(high_resolution_clock::now() - m_begin).count(); 28 } 29 //分 30 int64_t elapsed_minutes() const 31 { 32 return duration_cast<chrono::minutes>(high_resolution_clock::now() - m_begin).count(); 33 } 34 //时 35 int64_t elapsed_hours() const 36 { 37 return duration_cast<chrono::hours>(high_resolution_clock::now() - m_begin).count(); 38 } 39 private: 40 time_point<high_resolution_clock> m_begin; 41 };
测试代码:
1 void fun()
2 {
3 cout<<”hello word”<<endl;
4 }
5 int main()
6 {
7 timer t; //开始计时
8 fun()
9 cout<<t.elapsed()<<endl; //打印fun函数耗时多少毫秒
10 cout<<t.elapsed_micro ()<<endl; //打印微秒
11 cout<<t.elapsed_nano ()<<endl; //打印纳秒
12 cout<<t.elapsed_seconds()<<endl; //打印秒
13 cout<<t.elapsed_minutes()<<endl; //打印分钟
14 cout<<t.elapsed_hours()<<endl; //打印小时
15 }
标签:值类型 minutes std clu 第一个 标准 记录 代码 lap
原文地址:https://www.cnblogs.com/MrLiuZF/p/13977115.html