使用 gettimeofday 和 localtime 获得准确的时间戳
我正在尝试通过 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 吗?我假设 localtime 只是对 gettimeofday 的结果进行半昂贵的转换,因此它应该放在 printf 语句之前。
I'm attempting to monitor system time elapsed across multiple applications and data paths via gettimeoday and localtime. In this example, I want to grab the system time (microsecond percision) right before my code runs. I'm currently doing it like this:
#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);
From what I understand the localtime call definitely incurs a bit of overhead and can throw off accuracy. I might be totally wrong on this, but should I wait to call localtime until after my code to watch completes? I'm assuming that localtime is just doing a semi-expensive conversion of gettimeofday's results, and thus it should be placed right before the printf statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您确实需要微秒精度,是的。如果
localtime
在不到一微秒的时间内执行,我会感到非常惊讶。但如果 gettimeofday 具有微秒分辨率,我也会感到惊讶,即使实际计时器具有微秒分辨率(极不可能),从系统返回时的上下文切换可能会花费超过一微秒(并且可能比调用localtime
更长)。事实是,除非直接访问特殊硬件,否则您无法获得接近微秒的分辨率。If you really need microsecond accuracy, yes. I'd be very surprised if
localtime
executed in less than a microsecond. But I'd also be surprised ifgettimeofday
had a microsecond resolution, and even if the actual timer did (highly unlikely), the context switch when returning from the system will probably take well over a microsecond (and could be longer than the call tolocaltime
). The fact is that except when accessing special hardware directly, you can't get anywhere near microsecond resolution.