爲了安全起見,您應該初始化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)
請通過編輯來更好地格式化您的問題。這是不可讀的!使用以至少四個空格開頭的行代碼。 – 2014-09-01 11:40:48
'(Time.tv_sec * 1000000)'< - 可能的整數溢出,取決於您的平臺。 – 2014-09-01 11:43:08
你如何顯示它?與%d?嘗試%ld或者類似。 – jaroslawj 2014-09-01 11:45:29