2014-09-01 107 views
0

有時,我在下面的代碼中得到負值。 我不明白這一點。任何人都可以解釋爲什麼會發生。gettimeofday()有時候會返回負值

int64_t gettimelocal() 
{ 
    struct timeval Time; 
    if(-1 == gettimeofday(&Time,NULL)) 
    { 
     perror("gettimeofday"); 
    } 
    // get time in micro seconds 
    return ((Time.tv_sec * 1000000) + Time.tc_usec); 
} 
+0

請通過編輯來更好地格式化您的問題。這是不可讀的!使用以至少四個空格開頭的行代碼。 – 2014-09-01 11:40:48

+0

'(Time.tv_sec * 1000000)'< - 可能的整數溢出,取決於您的平臺。 – 2014-09-01 11:43:08

+0

你如何顯示它?與%d?嘗試%ld或者類似。 – jaroslawj 2014-09-01 11:45:29

回答

1

爲了安全起見,您應該初始化Time。當getttimeofday失敗時,您應該在perror後返回。所以嘗試:

int64_t gettimelocal() { 
    struct timeval Time = {0,0}; 
    if(-1 == gettimeofday(&Time,NULL)) { 
    perror("gettimeofday"); 
    return -1; 
    } 
    // get time in micro seconds 
    return (((int64_t)Time.tv_sec * 1000000) + Time.tv_usec); 
} 

最後,你確定乘法不溢出?您希望演員確定乘法是以64位完成的。

事實上,我會建議使用double浮點與clock_gettime(3)這樣的:

static inline double my_clock_time (clockid_t cid) { 
    struct timespec ts = { 0, 0 }; 
    if (clock_gettime (cid, &ts)) 
    return NAN; 
    else 
    return (double) ts.tv_sec + 1.0e-9 * ts.tv_nsec; 
} 

,並呼籲my_clock_time(CLOCK_REALTIME)

printf ("now %.5f\n", my_clock_time(CLOCK_REALTIME)); 

閱讀仔細time(7)。不要期望納秒精度!

用所有警告和調試信息編譯代碼(例如gcc -Wall -g)。使用調試器(gdb),也許strace(1)

相關問題