0

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.

Oleg Vazhnev
  • 23,239
  • 54
  • 171
  • 305

1 Answers1

2

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!

Nathilion
  • 309
  • 1
  • 7
  • Even more important is reading [time(7)](http://man7.org/linux/man-pages/man7/time.7.html) – Basile Starynkevitch Dec 23 '14 at 09:23
  • is it guaranteed that CLOCK_MONOTONIC_RAW can be used across physical processors? – Oleg Vazhnev Dec 23 '14 at 19:42
  • The monotonic clock is for the system. So, the way I read it is that no matter how many cores you have the time will be the same across all of them. It is answered in this SO question too: [Is clock monotonic process or thread specific.](https://stackoverflow.com/questions/4943733/is-clock-monotonic-process-or-thread-specific). – Nathilion Dec 25 '14 at 17:09