Why Is Clock_Gettime So Erratic

clock_gettime returning a nonsense value

tv_nsec is nanoseconds, i.e. 1 billionth (1 / 1,000,000,000) of one second. Your calcuation however is treating it as if it's microseconds.

Here's the fix:

return ((ts.tv_sec * 1000) + (ts.tv_nsec / 1000000)) + 0.5;
^^^

clock_gettime returns some very large value

Check function results.

Code had unexpected output, yet lacks a simple check to see if setting the time worked @Steve Summit. I'd expect this as an early debug step.

// clock_settime(CLOCK_REALTIME,&SysTime_Test);
if (clock_settime(CLOCK_REALTIME,&SysTime_Test)) {
puts("Fail Set");
}

Use correct *printf() specifiers

Member tv_nsec is a long. Print with "%ld". @Antti Haapala

printf("%ld", SysTime_Test.tv_nsec);

tv_sec is a time_t. On Linux systems that must be some integer type @Andrew Henle. Cast to the widest (or at least a wide) type and print.

printf("%jd", (intmax_t) SysTime_Test.tv_sec);
// or
printf("%lld", (long long) SysTime_Test.tv_sec);

Save time

Turn on all compiler warnings to detect issues quicker.

Be clear

"clock_gettime returns some very large value" --> not really. The function returned 0 every time as expected and printed. It was the values in SysTime_Test the appear unexpected certainly because they were not printed properly.

Is clock_gettime() adequate for submicrosecond timing?

No. You'll have to use platform-specific code to do it. On x86 and x86-64, you can use 'rdtsc' to read the Time Stamp Counter.

Just port the rdtsc assembly you're using.

__inline__ uint64_t rdtsc(void) {
uint32_t lo, hi;
__asm__ __volatile__ ( // serialize
"xorl %%eax,%%eax \n cpuid"
::: "%rax", "%rbx", "%rcx", "%rdx");
/* We cannot use "=A", since this would use %rax on x86_64 and return only the lower 32bits of the TSC */
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return (uint64_t)hi << 32 | lo;
}


Related Topics



Leave a reply



Submit