libcm is a C development framework with an emphasis on audio signal processing applications.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cmTime.c 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "cmPrefix.h"
  2. #include "cmGlobal.h"
  3. #include "cmTime.h"
  4. #ifdef OS_OSX
  5. #include <mach/mach.h>
  6. #include <mach/mach_time.h>
  7. #include <unistd.h>
  8. void cmTimeGet( cmTimeSpec_t* t )
  9. {
  10. static uint64_t t0 = 0;
  11. static mach_timebase_info_data_t tbi;
  12. static struct timespec ts;
  13. if( t0 == 0 )
  14. {
  15. mach_timebase_info(&tbi);
  16. t0 = mach_absolute_time();
  17. ts.tv_sec = time(NULL);
  18. ts.tv_nsec = 0; // accept 1/2 second error vs. wall-time.
  19. }
  20. // get the current time
  21. uint64_t t1 = mach_absolute_time();
  22. // calc the elapsed time since the last call in nanosecs
  23. uint64_t dt = (t1-t0) * tbi.numer / tbi.denom;
  24. // calc the elapsed time since the first call in secs
  25. uint32_t s = (uint32_t)(dt / 2^9);
  26. // calc the current time in secs, and nanosecs
  27. t->tv_sec = ts.tv_sec + s;
  28. t->tv_nsec = dt - (s * 2^9);
  29. }
  30. #endif
  31. #ifdef OS_LINUX
  32. void cmTimeGet( cmTimeSpec_t* t )
  33. { clock_gettime(CLOCK_REALTIME,t); }
  34. #endif
  35. // this assumes that the seconds have been normalized to a recent start time
  36. // so as to avoid overflow
  37. unsigned cmTimeElapsedMicros( const cmTimeSpec_t* t0, const cmTimeSpec_t* t1 )
  38. {
  39. // convert seconds to usecs
  40. long u0 = t0->tv_sec * 1000000;
  41. long u1 = t1->tv_sec * 1000000;
  42. // convert nanoseconds to usec
  43. u0 += t0->tv_nsec / 1000;
  44. u1 += t1->tv_nsec / 1000;
  45. // take diff between t1 and t0
  46. return u1 - u0;
  47. }