用于获取更高精度的当前时间,包括微秒,适合高精度时间测量。
1.头文件
#include <sys/time.h>
2.函数原型
int gettimeofday(struct timeval *tv, struct timezone *tz);
3.参数
tv:这是一个指向 struct timeval 结构的指针,用于存储当前的时间。struct timeval 结构包含两个字段:
tv_sec: 从 Unix 纪元(1970 年 1 月 1 日 00:00:00 UTC)开始的秒数。
tv_usec: 额外的微秒数(范围为 0 到 999999),提供更高的时间精度。
tz: 这是一个指向 struct timezone 结构的指针,通常用于存储时区信息。在现代应用中,通常将其设置为 NULL,因为大多数操作系统提供更为一致的时间管理方式。struct timezone 包含两个字段:
tz_minuteswest: UTC 和本地时间之间的分钟差。
tz_dsttime: 夏令时的类型。
4.返回值
函数返回值为 0 表示成功,返回 -1 表示失败,错误信息可通过 errno 获取。
5.示例:(使用gettimeofday获取当前时间)
| #include <stdio.h>
#include <sys/time.h> #include <time.h> #include <unistd.h> int main() { struct timeval tv; struct timezone tz; // 获取当前时间 if (gettimeofday(&tv, NULL) == -1) { perror("gettimeofday"); return 1; } // 输出时间 printf("Seconds since epoch: %ldn", tv.tv_sec); printf("Microseconds: %ldn", tv.tv_usec); // 将秒数转换为可读的时间格式 time_t seconds = tv.tv_sec; struct tm *timeinfo = localtime(&seconds); printf("Current local time: %s", asctime(timeinfo)); return 0; } |
6.查看测试结果
| Seconds since epoch: 1730945897
Microseconds: 76586 Current local time: Thu Nov 7 10:18:17 2024 |
275