linux 统计 程序 运行时间

本文介绍如何使用Linux系统中的gettimeofday()函数来精确测量代码的运行时间,通过实例演示了如何定义并利用struct timeval结构体变量记录开始与结束时刻,并计算出运行时间。

测试 代码运行时间

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

转载于:https://www.cnblogs.com/spinsoft/p/3767549.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值