monotonic.c 692 B

12345678910111213141516171819202122232425262728293031323334
  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <sys/time.h>
  5. #include <sys/types.h>
  6. #include <sys/sysctl.h>
  7. static double cpufrequency = 0;
  8. static void init(void)
  9. {
  10. long result = 0; size_t resultlen = sizeof(long);
  11. sysctlbyname("machdep.tsc_freq",&result,&resultlen,0,0);
  12. cpufrequency = result;
  13. }
  14. long long cpucycles_monotonic(void)
  15. {
  16. double result;
  17. struct timespec t;
  18. if (!cpufrequency) init();
  19. clock_gettime(CLOCK_MONOTONIC,&t);
  20. result = t.tv_nsec;
  21. result *= 0.000000001;
  22. result += (double) t.tv_sec;
  23. result *= cpufrequency;
  24. return result;
  25. }
  26. long long cpucycles_monotonic_persecond(void)
  27. {
  28. if (!cpufrequency) init();
  29. return cpufrequency;
  30. }