关于C/C++获取事件,计算时间差方式
关于C++获取事件,计算时间差方式
方案1:clock_t
方案2:gettimeofday
方案3:high_resolution_clock
代码如下:
1 #include <iostream> 2 #include <memory> 3 #include <sys/time.h> //for gettimeofday 4 #include <unistd.h> 5 #include <thread> 6 #include <time.h> //for clock_t 7 #include <chrono> //for high_resolution_clock 8 9 using std::chrono::high_resolution_clock; 10 using std::chrono::milliseconds; 11 12 using namespace std; 13 14 15 int main(int argc, char *argv[]) 16 { 17 int64_t sleeptime = 3; 18 cout << "sleeptime: "<< sleeptime << " ms" << endl; 19 //////clock_t////// 20 clock_t start; 21 clock_t end; 22 start = clock(); 23 24 this_thread::sleep_for(chrono::milliseconds(sleeptime)); 25 26 end = clock(); 27 cout << "the clock_t start: "<< start << " ms, end: " << end << " ms" << endl; 28 cout << "the clock_t func time span: "<< end - start << " ms" << endl; 29 //////gettimeofday////// 30 struct timeval start_time; 31 struct timeval stop_time; 32 33 gettimeofday(&start_time, NULL); 34 this_thread::sleep_for(chrono::milliseconds(sleeptime)); 35 gettimeofday(&stop_time, NULL); 36 37 cout << "the gettimeofday start: "<< (start_time.tv_sec*1000 + start_time.tv_usec/1000) << " ms, end: " << (stop_time.tv_sec*1000 + stop_time.tv_usec/1000) << " ms"<< endl; 38 long start_1 = (start_time.tv_sec*1000 + start_time.tv_usec/1000); 39 long stop_1 = (stop_time.tv_sec*1000 + stop_time.tv_usec/1000); 40 41 cout << "the gettimeofday time span: "<< stop_1 - start_1 << " ms" << endl; 42 43 //////high_resolution_clock////// 44 high_resolution_clock::time_point beginTime = high_resolution_clock::now(); 45 46 //sleep(3); //延时 47 this_thread::sleep_for(chrono::milliseconds(sleeptime)); 48 49 high_resolution_clock::time_point endTime = high_resolution_clock::now(); 50 51 milliseconds timeInterval = std::chrono::duration_cast<milliseconds>(endTime - beginTime); 52 53 cout << "the high_resolution_clock time span: "<< timeInterval.count() << " ms\n"; 54 55 return 0; 56 }
运行结果如下:
sleeptime: 3 ms
the clock_t start: 2751 ms, end: 2781 ms
the clock_t func time span: 30 ms
the gettimeofday start: 1597892088378 ms, end: 1597892088382 ms
the gettimeofday time span: 4 ms
the high_resolution_clock time span: 3 ms
运行多次,结论如下:
精确度:high_resolution_clock > gettimeofday > clock_t

浙公网安备 33010602011771号