misc.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Public Domain.
  2. #include <time.h>
  3. // *performance* time counting functions
  4. // these use CLOCK_MONOTONIC_RAW (>= Linux 2.6.28)
  5. // they do not provide a real unix timestamp, rather a consistent, precise measure of
  6. // some undefined time that is unaffected by system time twiddling
  7. double getCurrentTimePerf(void) { // in seconds
  8. double now;
  9. struct timespec ts;
  10. static double offset = 0;
  11. // CLOCK_MONOTONIC_RAW in >= Linux 2.6.28.
  12. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  13. now = (double)ts.tv_sec + ((double)ts.tv_nsec / 1000000000.0);
  14. if(offset == 0) offset = now;
  15. return now - offset;
  16. }
  17. double timeSincePerf(double past) {
  18. double now = getCurrentTimePerf();
  19. return now - past;
  20. }
  21. // these give unix timestamps
  22. // this function provides the number of seconds since the unix epoch
  23. double getCurrentTimeEpoch(void) { // in seconds
  24. double now;
  25. struct timespec ts;
  26. static double offset = 0;
  27. // CLOCK_MONOTONIC_RAW in >= Linux 2.6.28.
  28. clock_gettime(CLOCK_REALTIME, &ts);
  29. now = (double)ts.tv_sec + ((double)ts.tv_nsec / 1000000000.0);
  30. if(offset == 0) offset = now;
  31. return now - offset;
  32. }
  33. // deceptively but consistently named, this function is comparative with stamps
  34. // provided by the previous function
  35. double timeSinceEpoch(double past) {
  36. double now = getCurrentTimeEpoch();
  37. return now - past;
  38. }