开发者

Accurate Timestamps using gettimeofday and localtime

开发者 https://www.devze.com 2023-03-04 09:11 出处:网络
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

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 lo开发者_StackOverflowcaltime is just doing a semi-expensive conversion of gettimeofday's results, and thus it should be placed right before the printf statement.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消