在 unix 中获取本地时间的最快方法

Fastest way to get local time in unix

本文关键字:方法 时间 unix 获取      更新时间:2023-10-16

我正在研究Unix系统上的日志记录性能。问题是我发现最昂贵的操作是获取日期。

目前我有这样的时间——

timeb currTime;
struct tm localTime;
ftime( &currTime )
localtime_r(&currTime.time, &localTime);

我把它改成了

struct timeval tv;
gettimeofday(&tv, NULL); 
time_t curtime = tv.tv_sec;
struct tm localTime = *(localtime(&curtime));

并且没有看到任何性能改进。所以我想知道也许这不是在 unix 系统上获取本地时间的最快方法?

请分享你对此的看法。

提前感谢。

gettimeofday可以非常快速地为您提供UTC时间。 转换为本地时间不是那么快。

将其转换为本地时间,直到您脱离性能关键路径。

此外,您还可以每天一次缓存 UTC 到本地时间转换因子,以加快到本地时间的转换速度,尽管这并不完美,但对于日志记录目的来说可能已经足够了。