码迷,mamicode.com
首页 > 系统相关 > 详细

linux 统计 程序 运行时间

时间:2014-06-02 19:08:37      阅读:337      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

测试 代码运行时间

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

bubuko.com,布布扣
 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 timezone
11      * {
12      *     int tz_minuteswest;   // minutes west of Greenwich
13      *     int tz_dsttime;       // type of DST correction
14      * }
15      **********************************************/
bubuko.com,布布扣

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

bubuko.com,布布扣
 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 time
12     //-------------------------
13     
14     // test code
15     while(i)
16     {
17         i--;
18     }
19 
20     //-------------------------
21     gettimeofday(&end, NULL);  // get the end time
22     //-------------------------
23     
24     long long total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond
25     printf("total time is %lld us\n", total_time);
26     total_time /= 1000; // get the run time by millisecond
27     printf("total time is %lld ms\n", total_time);
28 }

测试结果:(CentOS 6.5, gcc 4.4.7)
total time is 49658 us
total time is 49 ms
bubuko.com,布布扣

 

linux 统计 程序 运行时间,布布扣,bubuko.com

linux 统计 程序 运行时间

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/molly/p/3764351.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!