我正在尝试通过 gettimeoday 和 localtime 监视跨多个应用程序和数据路径的系统时间。在这个例子中,我想在我的代码运行之前获取系统时间(微秒精度)。我目前正在这样做:
#include <stdio.h>
#include <sys/time.h>
struct timeval tv;
struct timezone tz;
struct tm *tm;
**code I don't care about**
gettimeofday(&tv, NULL);
tm=localtime(&tv.tv_sec);
**code to watch**
printf(" %d:%02d:%02d %ld \n", tm->tm_hour, tm->tm_min,
tm->tm_sec, tv.tv_usec);
据我了解,本地时间调用肯定会产生一些开销,并且会降低准确性。我可能完全错了,但我应该等到我的代码完成后才调用本地时间吗?我假设 localtime 只是对 gettimeofday 的结果进行半昂贵的转换,因此它应该放在 printf 语句之前。