SDL_systimer.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_TIMER_DOS
  20. #include <dos.h> /* delay */
  21. #include <time.h> /* uclock, uclock_t, UCLOCKS_PER_SEC */
  22. #include "../../core/dos/SDL_dos_scheduler.h"
  23. /* DJGPP's uclock() reprograms PIT channel 0 for a higher tick rate on first
  24. call, giving ~1.19 MHz resolution (UCLOCKS_PER_SEC == 1193180). This is
  25. the same approach SDL2-dos used and gives sub-microsecond precision without
  26. any extra setup. */
  27. Uint64 SDL_GetPerformanceCounter(void)
  28. {
  29. return (Uint64)uclock();
  30. }
  31. Uint64 SDL_GetPerformanceFrequency(void)
  32. {
  33. return (Uint64)UCLOCKS_PER_SEC;
  34. }
  35. void SDL_SYS_DelayNS(Uint64 ns)
  36. {
  37. if (ns == 0) {
  38. DOS_Yield();
  39. return;
  40. }
  41. const uclock_t delay_start = uclock();
  42. const uclock_t target_ticks = (uclock_t)((ns * UCLOCKS_PER_SEC) / SDL_NS_PER_SECOND);
  43. while ((uclock() - delay_start) < target_ticks) {
  44. /* Always yield first so cooperative threads can run. */
  45. DOS_Yield();
  46. /* If more than 1 ms remains, do a short sleep to avoid burning
  47. 100% CPU when no other threads need to run. DJGPP's delay()
  48. is a busy-wait but it does halt-loop on the PIT, which is
  49. lighter than a tight uclock() poll. */
  50. uclock_t remaining = target_ticks - (uclock() - delay_start);
  51. if (remaining > (UCLOCKS_PER_SEC / 1000)) {
  52. delay(1);
  53. }
  54. }
  55. }
  56. #endif /* SDL_TIMER_DOS */