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
How to Copy an Array in Nasm X86 Assembly for Linux, Porting 16-Bit Dos Code
Which Real-Time Priority Is the Highest Priority in Linux
Why Is Clock_Gettime So Erratic
How to Remove the Win10's Path from Wsl
How to Access an Environment Variable in a .Desktop File's Exec Line
Sed - Pass Match to External Command
Using <Linux/Types.H> in User Programs, or <Stdint.H> in Driver Module Code...Does It Matter
Multiple Ble Connections Using Linux and Bluez 5.0
Install Rabbitmqadmin on Linux
Linux Kernel Config_Debug_Section_Mismatch Make Errors
Bpf Verifier Rejects Code: "Invalid Bpf_Context Access"
Setting a Gdb Exit Breakpoint Not Working
Iterate Over Lines Instead of Words in a for Loop of Shell Script
Why Do I Have to Use Bash -L -C Inside My Container
Android Sdk on a 64-Bit Linux MAChine
How to Enable Tab-Completion of Command Line Switches in Bash