linux 统计 程序 运行时间

王朝学院·作者佚名  2016-05-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

linux 统计 程序 运行时间测试 代码运行时间

linux 中的 <sys/time.h> 中 有个函数可以获取当前时间,精确到 微秒 ----> gettimeofday()

1 #include <sys/time.h> // int gettimeofday(struct timeval *tv, struct timezone *tz); 2 /********************************************* 3 * struct timeval 4 * { 5 * time_t tv_sec; // seconds 6 * suseconds_t tv_usec; // microseconds:微秒 10^(-6)s, 这里的 tv_sec 用的是 微秒 7 * // millisecond :毫秒 10^(-3)s 8 * } 9 **********************************************10 * struct timezone11 * {12 * int tz_minuteswest; // minutes west of Greenwich13 * int tz_dsttime; // type of DST correction14 * }15 **********************************************/

使用时,定义两个 struct timeval 变量(通常 gettimeofday() 的第二个参数 设为 NULL),分别保存 代码测试 前后的时刻,最后相减,即可获取 代码运行时间 (可转换为自己需要的时间)。

1 #include <stdio.h> 2 #include <sys/time.h> // for gettimeofday() 3 #include <string.h> // for memset() 4 5 int main() 6 { 7 int i = 10000000; 8 struct timeval start, end; // define 2 struct timeval variables 9 10 //-------------------------11 gettimeofday(&start, NULL); // get the beginning time12 //-------------------------13 14 // test code15 while(i)16 {17 i--;18 }19 20 //-------------------------21 gettimeofday(&end, NULL); // get the end time22 //-------------------------23 24 long long total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond25 PRintf("total time is %lld us\n", total_time);26 total_time /= 1000; // get the run time by millisecond27 printf("total time is %lld ms\n", total_time);28 }测试结果:(CentOS 6.5, gcc 4.4.7)total time is 49658 ustotal time is 49 ms

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航