1
0

sleepto.c 902 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <windows.h>
  2. #include <stdbool.h>
  3. #include "sleepto.h"
  4. static bool have_clockfreq = false;
  5. static LARGE_INTEGER clock_freq;
  6. static inline uint64_t get_clockfreq(void)
  7. {
  8. if (!have_clockfreq) {
  9. QueryPerformanceFrequency(&clock_freq);
  10. have_clockfreq = true;
  11. }
  12. return clock_freq.QuadPart;
  13. }
  14. uint64_t gettime_100ns(void)
  15. {
  16. LARGE_INTEGER current_time;
  17. double time_val;
  18. QueryPerformanceCounter(&current_time);
  19. time_val = (double)current_time.QuadPart;
  20. time_val *= 10000000.0;
  21. time_val /= (double)get_clockfreq();
  22. return (uint64_t)time_val;
  23. }
  24. bool sleepto_100ns(uint64_t time_target)
  25. {
  26. uint64_t t = gettime_100ns();
  27. uint32_t milliseconds;
  28. if (t >= time_target)
  29. return false;
  30. milliseconds = (uint32_t)((time_target - t) / 10000);
  31. if (milliseconds > 1)
  32. Sleep(milliseconds - 1);
  33. for (;;) {
  34. t = gettime_100ns();
  35. if (t >= time_target)
  36. return true;
  37. Sleep(0);
  38. }
  39. }