Reputation: 24067
How can I print current system time with microsecond (or, better, nanosecond) precision? I need this time to be consistent between all system processors. If this is not possible than I want it to be consistent between all processor cores.
I've tried clock_gettime(CLOCK_REALTIME
but I suspect it produce different result at least when running on different processors.
Upvotes: 0
Views: 750
Reputation: 329
Sounds to me what you really want is CLOCK_MONOTONIC_RAW
(or just CLOCK_MONOTONIC
) . The raw clock measures time starting at a fixed point and queries a pure hardware-based clock. On Linux this fixed time point is the time of startup. Changes in the system time do not effect this clock (Summer/wintertime, etc.)
You can check the resolution of the clock in your system with a call to clock_getres(clockid_t clk_id, struct timespec *res);
Both gettime
and getres
take a timespec structure which holds two integers: seconds and nanoseconds. So the software is there, you just need a (hardware) clock capable of supplying the nanosecond resolution.
Man pages of the two functions:
http://man7.org/linux/man-pages/man2/clock_gettime.2.html & http://linux.die.net/man/3/clock_gettime
If you have access to the book "Linux Programming Interface" by Michael Kerrisk check out chapter 23 paragraph 5 (POSIX Clocks). When it comes to basic Linux programming this book has given me more answers than even StackOverflow has!
Upvotes: 2