您的位置:首页 > 运维架构 > Linux

C语言linux环境下使用gettimeofday函数得到程序运行时间

2016-10-18 23:13 1071 查看
编写的一个打字游戏中需要计算程序的运行时间,通过网上查阅资料发现大多数都是说通过clock()函数来获取时间,之后做差从而的到程序的运行时间。但是在linux中测试以后发现结果是0,并不能得到程序的运行时间。

请教老师后得知可以通过引用头文件time.h,使用gettimeofday()函数。

通过man gettimeifday可以查看详细信息:

SYNOPSIS
#include <sys/time.h>

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

DESCRIPTION
The  functions  gettimeofday()  and  settimeofday() can get and set the
time as well as a timezone.  The tv argument is a  struct  timeval  (as
specified in <sys/time.h>):

struct timeval {
time_t      tv_sec;     /* seconds */
suseconds_t tv_usec;    /* microseconds */
};

and  gives  the number of seconds and microseconds since the Epoch (see
time(2)).  The tz argument is a struct timezone:

struct timezone {
int tz_minuteswest;     /* minutes west of Greenwich */
int tz_dsttime;         /* type of DST correction */
};


函数会将系统时间存储到参数 struct timeval中,结构体中的两个变量分别为时间秒和微秒,timezone设为NULL即可。

用于计算程序运行时间只需在函数调用前后分别通过gettimeofday获取时间做差即可求得。

下面为代码用例:

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

int main()
{
struct timeval start,end;
gettimeofday(&start,NULL);
sleep(1);//需要测定时间的代码部分
gettimeofday(&end,NULL);
suseconds_t msec = end.tv_usec-start.tv_usec;
time_t sec = end.tv_sec-start.tv_sec;
printf("time used:%u.%us\n",sec,msec);
return 0;
}


运行结果:



测试环境为linux redhat系统。多次运行时间在微秒上会有所差别,在虚拟机上波动会有点大。

这里直接将微秒的差作为秒的小数部分,换算上还有些错误需要改进。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: