c++11 chrono全面解析(高精度时钟,可达纳秒级别)
前言
常用
睡眠
#include <chrono>
#include <thread>
void main(){
std::this_thread::sleep_for(std::chrono:: milliseconds (1000)); //休眠1000毫秒
}
获得当前程序运行毫秒
#include <ctime>
void main(){
int tick=(int)(std::clock()*1000/ CLOCKS_PER_SEC);
}
计时
方法1
#include <chrono>
#include <thread>
void main(){
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono:: milliseconds (2000));
auto end = std::chrono::high_resolution_clock::now();
uint64_t time = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
printf("time:%ld\n",time);
}
方法2
#include <chrono>
#include <thread>
void main(){
auto start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
std::this_thread::sleep_for(std::chrono:: milliseconds (2000));
uint64_t cur_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
uint64_t spend_time = cur_time - start ;
printf("time:%ld\n", spend_time);
}