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
标签:std,clock,chrono,C++,获取,point,time
From: https://www.cnblogs.com/yongchao/p/17304755.html