|
通过调用 time() 函数可以得到 low-level 的时间值,这个值是从纪元(UNIX 和 Linux 系统从 1970年开始记起)开始到现在位置的秒数。如果参数 tloc 不是个空指针的话,time() 函数也把值返回到由 tloc 指针所指向的位置。
函数原型:
#include <time.h>
time_t time(time_t *tloc);
用法示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main()
{
int i;
time_t the_time;
for(i = 1; i <= 10; i++) {
the_time = time((time_t *)0);
printf("The time is %ld\n", the_time);
sleep(2);
}
exit(0);
} 运行结果输出:[root@localhost C]# ./envtime.exe
The time is 1235037957
The time is 1235037959
The time is 1235037961
The time is 1235037963
The time is 1235037965
The time is 1235037967
The time is 1235037969
The time is 1235037971
The time is 1235037973
The time is 1235037975
可以简单的考虑使用两次调用 time() 函数得到的值进行相减得到时间差。然而,经过深思熟虑,ISO/ANSIC 标准委员会并没有指定用 time_t 来计算秒间的任意时间间隔。所以,他们发明了一个叫做 difftime() 的函数,这个函数可以在短时间内计算两个 time_t 值间的差值,返回的是一个 double 型。
函数原型:
#include <time.h>
double difftime(time_t time1, time_t time2);
difftime 函数计算两个时间值之间的不同并返回一个与 time1-time2 的值,这个值为浮点形式。对于 Linux , time() 返回的值为一个秒数,可以对其操作使用。但对于追求轻便的话,建议使用 difftime() .
difftime() 函数示例:#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main()
{
time_t the_time_1;
time_t the_time_2;
the_time_1 = time((time_t *)0);
printf("The time is %ld\n", the_time_1);
sleep(2);
the_time_2 = time((time_t *)0);
printf("The time is %ld\n", the_time_2);
printf("Difftime returns is: %e\n", difftime(the_time_2, the_time_1));
exit(0);
}
运行及输出:[root@localhost C]# ./envtime.exe
The time is 1235044467
The time is 1235044469
Difftime returns is: 2.000000e+00 |
|