输出程序运行的时间(精确到微秒)

对于要求性能的代码,输出程序运行的时间还是很有必要的,而且需要较高的精确度,下面这个代码段就实现了此功能

注意:只限于Linux下使用,因为<sys/time.h>的缘故

 1 #include <sys/time.h>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int main(int argc, char **argv)
 7 {
 8     // 统计所用时间
 9     unsigned int unTimeUse;
10 
11     struct timeval stStartTime;
12     struct timeval stEndTime;
13     
14     gettimeofday(&stStartTime, NULL);
15     
16     int i = 10000;
17     while(i-- > 0);
18     
19     gettimeofday(&stEndTime, NULL);
20     unTimeUse = 1000000*(stEndTime.tv_sec - stStartTime.tv_sec) + 
21         stEndTime.tv_usec - stStartTime.tv_usec;
22         
23     cout.setf(ios_base::fixed); 
24     cout << "Use time: " << unTimeUse/1000000.0 << " sec" << endl;
25 
26     return 0;
27 }

输出结果:

原文地址:https://www.cnblogs.com/lit10050528/p/4013992.html