monotonic.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #ifndef __MONOTONIC_H
  2. #define __MONOTONIC_H
  3. /* The monotonic clock is an always increasing clock source. It is unrelated to
  4. * the actual time of day and should only be used for relative timings. The
  5. * monotonic clock is also not guaranteed to be chronologically precise; there
  6. * may be slight skew/shift from a precise clock.
  7. *
  8. * Depending on system architecture, the monotonic time may be able to be
  9. * retrieved much faster than a normal clock source by using an instruction
  10. * counter on the CPU. On x86 architectures (for example), the RDTSC
  11. * instruction is a very fast clock source for this purpose.
  12. */
  13. #include "fmacros.h"
  14. #include <stdint.h>
  15. #include <unistd.h>
  16. /* A counter in micro-seconds. The 'monotime' type is provided for variables
  17. * holding a monotonic time. This will help distinguish & document that the
  18. * variable is associated with the monotonic clock and should not be confused
  19. * with other types of time.*/
  20. typedef uint64_t monotime;
  21. /* Retrieve counter of micro-seconds relative to an arbitrary point in time. */
  22. extern monotime (*getMonotonicUs)(void);
  23. /* Call once at startup to initialize the monotonic clock. Though this only
  24. * needs to be called once, it may be called additional times without impact.
  25. * Returns a printable string indicating the type of clock initialized.
  26. * (The returned string is static and doesn't need to be freed.) */
  27. const char * monotonicInit();
  28. /* Functions to measure elapsed time. Example:
  29. * monotime myTimer;
  30. * elapsedStart(&myTimer);
  31. * while (elapsedMs(myTimer) < 10) {} // loops for 10ms
  32. */
  33. static inline void elapsedStart(monotime *start_time) {
  34. *start_time = getMonotonicUs();
  35. }
  36. static inline uint64_t elapsedUs(monotime start_time) {
  37. return getMonotonicUs() - start_time;
  38. }
  39. static inline uint64_t elapsedMs(monotime start_time) {
  40. return elapsedUs(start_time) / 1000;
  41. }
  42. #endif