您的位置:首页 > 其它

利用gettimeofday简单测试程序用时

2016-02-24 15:41 561 查看
centos$ man 2 gettimeofday


#include <sys/time.h>

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

struct timeval {
time_t tv_sec;      // seconds
suseconds_t tv_usec;   //microseconds
};
// it gives the number of seconds and microseconds since the Epoch (see time(2))

struct timezone {
int tz_minuteswest; //minutes west of Greenwich
int tz_dsttime;    //type of DST correction
};
// if tv or tz is NULL, the corresponding structure is no set or returned.


简单测试用例

程序中添加两个struct timeval 来记录开始和完成的时间就可以了。

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

int main()
{
struct timeval beginTime, endTime;
if (gettimeofday(&beginTime, NULL) == -1)
return -1;

for (int i = 1; i <= 10000; i++)
for (int j = 1; j <= 10000; j++)
;

if (gettimeofday(&endTime, NULL) == -1)
return -1;

double seconds;
seconds = 1000000*(endTime.tv_sec - beginTime.tv_sec) + (endTime.tv_usec - beginTime.tv_usec);
seconds /= 1000000;

printf("using time : %f\n", seconds);

return 0;
}


运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: