链接
std::chrono是C++11引入的日期时间处理库,其中包含3种时钟:
system_clock,steady_clock,high_resolution_clock。
定义于头文件 <chrono>
std::chrono
库
system_clock
steady_clock
链接
链接2
每一次调用time_point都是记录一次从1970年1月1日到现在的秒数
单位:秒;
精度:纳秒
std::chrono::steady_clock::time_point tp1=std::chrono::steady_clock::now();std::cout<<"1970.1.1-----now:"<<tp1.time_since_epoch().count()<<std::endl;int i=100;while(i) i--;std::chrono::steady_clock::time_point tp2=std::chrono::steady_clock::now();std::chrono::duration<double> dur=tp2-tp1;std::cout<<"time duratino="<<dur.count()<<std::endl;
high_resolution_clock
std::chrono::time_point<>
类模板,记录的是三种时钟的一种返回的时间点。
第一种使用方法:
#include <iostream>#include <chrono>int main(){std::chrono::steady_clock::time_point t1 = std::chrono::system_clock::now();std::cout << "Hello World\n";std::chrono::steady_clock::time_point t2 = std::chrono:: system_clock::now();std::cout << (t2-t1).count()<<” tick count”<<endl;}
第二种使用方法:
#include <iostream>#include <chrono>int main(){std::chrono::time_point<std::chrono::steady_clock> t1 = std::chrono::system_clock::now();std::cout << "Hello World\n";std::chrono::time_point<std::chrono::steady_clock> t2 = std::chrono:: system_clock::now();std::cout << (t2-t1).count()<<” tick count”<<endl;}
std::chrono::duration<>
记录时钟的时间间隔,
#include <iostream>
#include <vector>
#include <numeric>
#include <chrono>volatile int sink;
int main()
{for (auto size = 1ull; size < 1000000000ull; size *= 100){// 记录开始时间auto start = std::chrono::steady_clock::now();// 做一些工作std::vector<int> v(size, 100);sink = std::accumulate(v.begin(), v.end(), 0u); // 记录结束时间auto end = std::chrono::steady_clock::now();std::chrono::duration<double> diff = end - start;std::cout << std::fixed << "Time to fill and iterate a vector of "<< size << " ints : " << diff.count() << " s\n";}
}
time_since_epoch().count()
显示时间点的时间
std::chrono::steady_clock::now(); // 纳秒
uint64_t ui64MicroSecondsTp = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); // 微秒
uint64_t ui64MilliSecondsTp = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); // 毫秒
微秒,毫秒,纳秒
microseconds, milliseconds, nanoseconds