Linux下可以使用gettimeofday()来查看当前时间,这个函数会计算从1970年1月1号00:00(UTC)到当前的时间跨度。其函数原型如下,
#include <sys/time.h>
// 调用成功返回0,失败返回-1
int gettimeofday(struct timeval *tv, struct timezone *tz);
该函数所算出的时间跨度会存放在第一个参数tv里,这个参数的类型定义如下,
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
可以看出算出来的时间跨度可以精确到微妙,time_t和suseconds_t的实际类型是long int。日常使用时,只需传第一个参数,第二个参数传NULL(因为linux内核不会使用这个参数)。
举例
下面是个简单例子,计算当前时间,
#include <sys/time.h>
#include <stdio.h>
int main(void)
{
struct timeval val;
int ret = gettimeofday(&val, NULL);
if (ret == -1)
{
printf("Error: gettimeofday()\n");
return ret;
}
printf("sec: %ld, usec: %ld\n", val.tv_sec, val.tv_usec);
return 0;
}
打印输出,
一般来说,我们使用gettimeofday()多是用来计算时间差,下面是计算时间差的例子,
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
const unsigned long Converter = 1000 * 1000; // 1s == 1000 * 1000 us
int main(void)
{
struct timeval val;
int ret = gettimeofday(&val, NULL);
if (ret == -1)
{
printf("Error: gettimeofday()\n");
return ret;
}
sleep(2); // 睡眠2s
struct timeval newVal;
ret = gettimeofday(&newVal, NULL);
if (ret == -1)
{
printf("Error: gettimeofday()\n");
return ret;
}
printf("start: sec --- %ld, usec --- %ld\n", val.tv_sec, val.tv_usec);
printf("end: sec --- %ld, usec --- %ld\n", newVal.tv_sec, newVal.tv_usec);
unsigned long diff = (newVal.tv_sec * Converter + newVal.tv_usec) - (val.tv_sec * Converter + val.tv_usec);
printf("diff: sec --- %ld, usec --- %ld\n", diff / Converter, diff % Converter);
return 0;
}
打印输出如下,
可以看到时间差大约是2s