misc.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. // CLOCK_MONOTONIC_RAW in >= Linux 2.6.28.
  27. clock_gettime(CLOCK_REALTIME, &ts);
  28. now = (double)ts.tv_sec + ((double)ts.tv_nsec / 1000000000.0);
  29. return now;
  30. }
  31. // deceptively but consistently named, this function is comparative with stamps
  32. // provided by the previous function
  33. double timeSinceEpoch(double past) {
  34. double now = getCurrentTimeEpoch();
  35. return now - past;
  36. }