C++-C11-chrono-获取当前时间、获取阶段时间
C++-C11-chrono-获取当前时间、获取阶段时间
Linux下使用C++11的chrono库获取时间。
#include <chrono>
#include <thread>
#include <iostream>
int64_t getCurrentLocalTimeStamp(){
std::chrono::time_point<std::chrono::system_clock,
std::chrono::milliseconds> tp = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
auto tmp = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
return tmp.count();
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
char* print_time_point(std::chrono::system_clock::time_point timePoint) {
std::time_t timeStamp = std::chrono::system_clock::to_time_t(timePoint);
return std::ctime(&timeStamp);
}
int64_t getTimeSpan(){
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
/*
std::chrono::nanoseconds
std::chrono::microseconds
std::chrono::milliseconds
std::chrono::seconds
std::chrono::minutes
std::chrono::hours
template< class Clock, class Duration >
void sleep_until( const std::chrono::time_point<Clock,Duration>& sleep_time )
*/
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed = end - start;
return elapsed.count();
}
int main(){
std::cout<<getTimeSpan()<<std::endl;
std::cout<<getCurrentLocalTimeStamp()<<std::endl;
std::cout<<print_time_point(std::chrono::high_resolution_clock::now())<<std::endl;
return 0;
}
输出结果如下:
1000
1681140472905
Mon Apr 10 23:27:52 2023
double类型时间转换std::chrono::duration
近期封装的class Event中WaitFor()的参数需要const std::chrono::duration<_Rep, _Period> &duration,而传入的是double的值,所以做了以下转换。
double dStart;
double dEnd;
double dSpan = dEnd-dStart;
std::chrono::milliseconds ms{(int64_t)dSpan};
或
std::chrono::duration<double, std::milli> elpased = ms;
或
std::chrono::duration<double, std::milli> t(dSpan);
本文来自博客园,作者:Theseus‘Ship,转载请注明原文链接:https://www.cnblogs.com/yongchao/p/17304755.html