To be safe, you should initialize Time
. When getttimeofday
fails, you should return after the perror
. So try:
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);
}
At last, are you sure that the multiplication does not overflow? You want a cast to be sure the multiplication is done in 64 bits.
Actually, I would suggest using double
floating point with clock_gettime(3) like this:
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;
}
and call my_clock_time(CLOCK_REALTIME)
like
printf ("now %.5f\n", my_clock_time(CLOCK_REALTIME));
Read carefully time(7). Don't expect nanosecond accuracy!
Compile your code with all warnings and debug info (e.g. gcc -Wall -g
). Use the debugger (gdb
) and perhaps strace(1)