linux c 测试程序运行时间,Linux C下 统计 程序 运行时间

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

#include

// int gettimeofday(struct timeval *tv, struct timezone *tz);

/*********************************************

* struct timeval

* {

* time_t tv_sec; // seconds

* suseconds_t tv_usec; // microseconds:微秒 10^(-6)s, 这里的 tv_sec 用的是 微秒

* // millisecond :毫秒 10^(-3)s

* }

**********************************************

* struct timezone

* {

* int tz_minuteswest; // minutes west of Greenwich

* int tz_dsttime; // type of DST correction

* }

**********************************************/

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

#include

#include // for gettimeofday()

#include // for memset()

int main()

{

int i = 10000000;

struct timeval start, end; // define 2 struct timeval variables

//-------------------------

gettimeofday(&start, NULL); // get the beginning time

//-------------------------

// test code

while(i)

{

i--;

}

//-------------------------

gettimeofday(&end, NULL); // get the end time

//-------------------------

long long total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond

printf("total time is %lld us\n", total_time);

total_time /= 1000; // get the run time by millisecond

printf("total time is %lld ms\n", total_time);

}

测试结果:(CentOS 6.5, gcc 4.4.7)

total time is 49658 us

total time is 49 ms

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值