C语言获取时间的相关函数,包括如果获取微妙、毫秒级时间 在写程序的过程中,总是需要,或想去测试一段时间运行话费的时间,有需要测试秒级的,也许毫秒级的,但是有些更细微的程序我们需要测试其微秒级的时延。分别介绍如下:
1 微秒级的时延
1.1 timeval结构体 timeval结构体定义在time.h中:
struct timeval
{
__time_t tv_sec; /* Seconds. */
__suseconds_t tv_usec; /* Microseconds. */
};
其中,tv_sec为从1970-1-1零点零分到创建struct timeval时的秒数,tv_usec为微秒数。
注意:它是指从1970-1-1 0:0:0 零微秒至当前的时间差tv_sec秒
后面的零头
。所以,要想获取一个操作或子程序的运行毫秒或微秒级时长,不能简单实用前后两个时间采集点的tv_usec相减,否则会出现负值(如timeval_test_0.cpp),而应考虑到前后两个时间点的秒差(tv_sec)(见
timeval_test.cpp及其运行结果
)。
1.2 与timeval相关的gettimeofday()函数 :
该函数的注解为:
/* Get the current time of day and timezone information,
putting it into *TV and *TZ. If TZ is NULL, *TZ is not filled.
Returns 0 on success, -1 on errors.
NOTE: This form of timezone information is obsolete.
Use the functions and variables declared in instead. */
extern int gettimeofday (struct timeval *__restrict __tv,
__timezone_ptr_t __tz) __THROW __nonnull ((1));
gettimeofday()功能是得到当前时间和时区,分别写到tv和tz中,如果tz为NULL则不向tz写入。
1.3 源码与运行结果:
timeval_test_0.cpp:
#include
#include
#include
int main()
{
timeval start,end;
double d=23.345;
double k=324.917;
double s;
long dif_sec, dif_usec;
for(int i=0; i<10; i++)
{
gettimeofday(&start, NULL);
for(int j=0; j
{
s += k*j - d*(j+3);
}
gettimeofday(&end, NULL);
dif_sec = end.tv_sec - start.tv_sec;
dif_usec = end.tv_usec - start.tv_usec;
printf("running time for %d loop is %ldsec (%ld us)\n", i, dif_sec, dif_usec);
}