gettimeofday
函数功能
获取当前系统的时间,返回自1970年1月1日以来的秒数和微秒数。该函数适用于获取高精度的时间戳。
函数定义
int gettimeofday(struct timeval *tv, struct timezone *tz);
参数说明
参数名 |
描述 |
取值范围 |
输入/输出 |
---|---|---|---|
tv |
指向struct timeval的指针,返回当前时间的秒数和微秒数。 |
非空timeval结构体 |
输入/输出 |
tz |
指向struct timezone的指针,通常在现代系统中不再使用,因此通常设为NULL。 |
NULL |
输入 |
返回值
- 成功:返回0。
- 失败:对标开源Glibc,不返回特殊异常值。

gettimeofday提供的时间精度为微秒级。
示例
#include <stdio.h> #include <sys/time.h> #include <time.h> int main() { struct timeval tv; struct timezone *tz; int seconds; float micros; tz = NULL; gettimeofday(&tv, tz); seconds = tv.tv_sec; micros = tv.tv_usec; printf("当前时间(秒数):%ld\n", seconds); double timestamp = seconds + micros / 1.0e6; printf("高精度时间戳(秒数和微秒数):%f\n", timestamp); return 0; }
运行结果:
结果: 当前时间(秒数):*** 高精度时间戳(秒数和微秒数):***
父主题: 函数定义