使用 gettimeofday 和 localtime 获得准确的时间戳

发布于 2024-11-05 10:34:02 字数 610 浏览 0 评论 0原文

我正在尝试通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不乱于心 2024-11-12 10:34:02

如果您确实需要微秒精度,是的。如果 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 if gettimeofday 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 to localtime). The fact is that except when accessing special hardware directly, you can't get anywhere near microsecond resolution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文