When I output the microseconds field for gettimeofday(), I notice that the microsecond field is larger than 1,000,000. Does anyone know why this is? And does this imply that I've been interpreting gettimeofday() wrong?
For the record, my assumption is that the current time (in microseconds) according to gettimeofday() is the following:
struct timeval ts;
gettimeofday(&ts, NULL);
printf("%zu", ts.tv_sec * 1000000 + ts.tv_usec);
Edit: Here is the code that is causing the problem. After the comments below, the printf() might be at fault.
struct timeval curr_time;
gettimeofday(&curr_time, NULL);
printf("Done-arino! Onto the matrix multiplication (at %zu s, %03zu ms)\n", curr_time.tv_sec, curr_time.tv_usec);
// Matrix Multiplication
struct timeval start_tv, end_tv, elapsed_tv;
gettimeofday(&start_tv, NULL);
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
for (k = 0; k < N; k++)
C[i][j] += A[i][k] * B[k][j];
gettimeofday(&end_tv, NULL);
timersub(&end_tv, &start_tv, &elapsed_tv);
// Print results
printf("Elapsed time: %zu s, %03zu ms\n", elapsed_tv.tv_sec, elapsed_tv.tv_usec / 1000);
After a successful to
gettimeofday, yes,tv_usecis guaranteed to be strictly less than 1000000.If you (think you) saw a value of 1000000 or greater, then yes, it's likely you were doing something wrong.
A frequent mistake is to add or subtract two
struct timevalvalues naively, without implementing proper carry or borrow between thetv_secandtv_usecfields, and this can easily lead to (mistaken and wrong) values intv_usecgreater than 1000000. (In your edited post you mention subtracting timespecs, but you're using the system-suppliedtimersubfunction which ought to get the borrow right.)If you were using a
struct timespecinstead ofstruct timeval, and if a leap second were going on, and if you were (miraculously) using an OS kernel that implemented theCLOCK_UTCclock type proposed by Markus Kuhn at https://www.cl.cam.ac.uk/~mgk25/posix-clocks.html, you'd seetv_nsecvalues greater than 1000000000, but that's a lot of "if"s. (And to my knowledge no kernel in widespread use has ever implementedCLOCK_UTC.)