在Linux系统中,gettimeofday()
和 localtime()
是两个常用的时间处理函数,分别用于获取高精度时间戳和将时间戳转换为本地时间。以下是它们的概念和使用案例的详细说明:
gettimeofday()
函数Epoch
即 1970-01-01 00:00:00 UTC 起的秒数和微秒数)及系统的时区信息。#include
int gettimeofday(struct timeval *tv, struct timezone *tz);
tv
:指向 struct timeval
的指针,用于存储时间值。struct timeval {
time_t tv_sec; // 秒数
suseconds_t tv_usec; // 微秒数(0-999,999)
};
tz
:历史遗留参数,已废弃,应设为 NULL
。0
,失败返回 -1
。#include
#include
int main() {
struct timeval start, end;
gettimeofday(&start, NULL);
// 模拟耗时操作(例如循环)
for (int i = 0; i < 1000000; i++);
gettimeofday(&end, NULL);
// 计算时间差(微秒)
long seconds = end.tv_sec - start.tv_sec;
long micros = ((seconds * 1000000) + end.tv_usec) - start.tv_usec;
printf("耗时: %ld 微秒\n", micros);
return 0;
}
#include
#include
int main() {
struct timeval tv;
gettimeofday(&tv, NULL);
printf("时间戳: %ld秒 + %d微秒\n", tv.tv_sec, tv.tv_usec);
return 0;
}
tv_usec
的实际精度取决于系统实现(可能无法达到真正的微秒级)。clock_gettime()
(支持纳秒级精度,需指定 CLOCK_REALTIME
等时钟类型)。localtime()
函数time_t
类型的时间戳转换为本地时间的结构化表示(考虑时区)。#include
struct tm *localtime(const time_t *timer);
timer
指向 time_t
类型的时间戳。struct tm
的指针,包含以下成员:struct tm {
int tm_sec; // 秒(0-59)
int tm_min; // 分(0-59)
int tm_hour; // 时(0-23)
int tm_mday; // 日(1-31)
int tm_mon; // 月(0-11,需加1)
int tm_year; // 年(自1900年起)
int tm_wday; // 星期(0-6,0=周日)
int tm_yday; // 年中的第几天(0-365)
int tm_isdst; // 夏令时标志
};
#include
#include
int main() {
time_t rawtime;
struct tm *timeinfo;
time(&rawtime); // 获取当前时间戳
timeinfo = localtime(&rawtime); // 转换为本地时间
printf("当前时间: %d-%02d-%02d %02d:%02d:%02d\n",
timeinfo->tm_year + 1900, // 年份需加1900
timeinfo->tm_mon + 1, // 月份需加1
timeinfo->tm_mday,
timeinfo->tm_hour,
timeinfo->tm_min,
timeinfo->tm_sec);
return 0;
}
使用 strftime()
进一步格式化时间:
#include
#include
int main() {
time_t rawtime;
struct tm *timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", timeinfo);
printf("格式化时间: %s\n", buffer);
return 0;
}
localtime()
返回静态内存指针,多线程中应改用 localtime_r()
。struct tm *localtime_r(const time_t *timer, struct tm *result);
setenv("TZ", "时区名", 1)
调整。将 gettimeofday()
的高精度时间与 localtime()
的本地时间转换结合:
#include
#include
#include
int main() {
struct timeval tv;
gettimeofday(&tv, NULL);
time_t rawtime = tv.tv_sec;
struct tm *timeinfo = localtime(&rawtime);
printf("精确时间: %04d-%02d-%02d %02d:%02d:%02d.%06ld\n",
timeinfo->tm_year + 1900,
timeinfo->tm_mon + 1,
timeinfo->tm_mday,
timeinfo->tm_hour,
timeinfo->tm_min,
timeinfo->tm_sec,
tv.tv_usec);
return 0;
}
gettimeofday()
:获取高精度时间戳(秒+微秒),适合性能分析或日志记录。localtime()
:将时间戳转换为易读的本地时间结构,需注意线程安全和时区配置。clock_gettime()
,需线程安全时用 localtime_r()
。