Clock_gettime nanoseconds calculation
Because 5551 - 999896062 is some negative value, stored in a temp variable of type long, but interpreted by printf as "unsigned long" due to the %lu conversion specifier.
Note that the tv_nsec field in struct timespec is of type long, not unsigned long. Similarly, on Linux and other Unix systems time_t is a typedef for a signed integer type. So get rid of all the unsigned stuff in your code.
Btw, a way to to substract two timespec instances is
timespec diff(timespec start, timespec end)
{
timespec temp;
if ((end.tv_nsec - start.tv_nsec) < 0)
{
temp.tv_sec = end.tv_sec - start.tv_sec - 1;
temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
}
else
{
temp.tv_sec = end.tv_sec - start.tv_sec;
temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
return temp;
}
resting
Updated on June 05, 2022Comments
-
resting almost 2 years
ref: linux clock_gettime
I found a formula which works well to get the processing time, but there's something I don't understand. See the result below.
The first 2 rows is just to show the forumla in their respective columns.
I'm only showing 3 results from a quick run.
The interesting part is in the last row, why is5551 - 999896062
nanoseconds = 18446744072709661105?
Why is18446744072709661105+1/1E9
= 0.000109?I think there's some data conversion going on that affects the results?
xx: | t1.tv_sec | | t1.tv_nsec | | t2.tv_sec | | t2.tv_nsec xx: t2-t1(sec) t2-t1(nsec) (t2-t1(sec))+(t2-t1(nsec))/1E9 52291: | 30437 | | 999649886 | | 30437 | | 999759331 52291: 0 109445 0.000109 52292: | 30437 | | 999772970 | | 30437 | | 999882416 52292: 0 109446 0.000109 52293: | 30437 | | 999896062 | | 30438 | | 5551 52293: 1 18446744072709661105 0.000109
source code:
int main() { struct timespec t1, t2; int i = 0; while(1) { clock_gettime(CLOCK_MONOTONIC, &t1); for(int j=0;j<25000;j++) { }; clock_gettime(CLOCK_MONOTONIC, &t2); printf("%d: \t | %llu | \t | %lu | \t\t | %llu | \t | %lu \n", i, (unsigned long long) t1.tv_sec, t1.tv_nsec, (unsigned long long) t2.tv_sec, t2.tv_nsec); printf("%d: \t %llu \t %lu \t\t %lf\n", i, (unsigned long long) t2.tv_sec - t1.tv_sec, t2.tv_nsec - t1.tv_nsec, (t2.tv_sec - t1.tv_sec)+(t2.tv_nsec - t1.tv_nsec)/1E9); if ((t2.tv_sec - t1.tv_sec) == 1) break; i++; } return 0; }