【发布时间】:2017-08-05 04:20:36
【问题描述】:
我需要最快的方法来获取本地时间(因此考虑到当前时区),至少以毫秒为单位,如果可以在十分之一毫秒内获取它会更好。
我想避免使用 gettimeofday(),因为它现在是一个过时的函数。
所以,我似乎需要使用clock_gettime(CLOCK_REALTIME, ...) 并将小时调整为当前时区,但是如何?这样做的最佳点在哪里?在存储使用clock_gettime获得的时间戳之前,还是在将其转换为当前时区的公历之前?
编辑:我加入 get_clock 和 localtime 的原始示例 - 有更好的方法来实现吗?
#include <time.h>
#include <stdio.h>
int main() {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
struct tm* ptm;
ptm = localtime(&(ts.tv_sec));
// Tenths of milliseconds (4 decimal digits)
int tenths_ms = ts.tv_nsec / (100000L);
printf("%04d-%02d-%02d %02d:%02d:%02d.%04d\n",
1900 + ptm->tm_year, ptm->tm_mon + 1, ptm->tm_mday,
ptm->tm_hour, ptm->tm_min, ptm->tm_sec, tenths_ms);
}
【问题讨论】: