SDL_timer.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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. #include "SDL_timer_c.h"
  20. #include "../thread/SDL_systhread.h"
  21. // #define DEBUG_TIMERS
  22. #if !defined(SDL_PLATFORM_EMSCRIPTEN)
  23. typedef struct SDL_Timer
  24. {
  25. SDL_TimerID timerID;
  26. SDL_TimerCallback callback_ms;
  27. SDL_NSTimerCallback callback_ns;
  28. void *userdata;
  29. Uint64 interval;
  30. Uint64 scheduled;
  31. SDL_AtomicInt canceled;
  32. struct SDL_Timer *next;
  33. } SDL_Timer;
  34. typedef struct SDL_TimerMap
  35. {
  36. SDL_TimerID timerID;
  37. SDL_Timer *timer;
  38. struct SDL_TimerMap *next;
  39. } SDL_TimerMap;
  40. // The timers are kept in a sorted list
  41. typedef struct
  42. {
  43. // Data used by the main thread
  44. SDL_InitState init;
  45. SDL_Thread *thread;
  46. SDL_TimerMap *timermap;
  47. SDL_Mutex *timermap_lock;
  48. // Padding to separate cache lines between threads
  49. char cache_pad[SDL_CACHELINE_SIZE];
  50. // Data used to communicate with the timer thread
  51. SDL_SpinLock lock;
  52. SDL_Semaphore *sem;
  53. SDL_Timer *pending;
  54. SDL_Timer *freelist;
  55. SDL_AtomicInt active;
  56. // List of timers - this is only touched by the timer thread
  57. SDL_Timer *timers;
  58. } SDL_TimerData;
  59. static SDL_TimerData SDL_timer_data;
  60. /* The idea here is that any thread might add a timer, but a single
  61. * thread manages the active timer queue, sorted by scheduling time.
  62. *
  63. * Timers are removed by simply setting a canceled flag
  64. */
  65. static void SDL_AddTimerInternal(SDL_TimerData *data, SDL_Timer *timer)
  66. {
  67. SDL_Timer *prev, *curr;
  68. prev = NULL;
  69. for (curr = data->timers; curr; prev = curr, curr = curr->next) {
  70. if (curr->scheduled > timer->scheduled) {
  71. break;
  72. }
  73. }
  74. // Insert the timer here!
  75. if (prev) {
  76. prev->next = timer;
  77. } else {
  78. data->timers = timer;
  79. }
  80. timer->next = curr;
  81. }
  82. static int SDLCALL SDL_TimerThread(void *_data)
  83. {
  84. SDL_TimerData *data = (SDL_TimerData *)_data;
  85. SDL_Timer *pending;
  86. SDL_Timer *current;
  87. SDL_Timer *freelist_head = NULL;
  88. SDL_Timer *freelist_tail = NULL;
  89. Uint64 tick, now, interval, delay;
  90. /* Threaded timer loop:
  91. * 1. Queue timers added by other threads
  92. * 2. Handle any timers that should dispatch this cycle
  93. * 3. Wait until next dispatch time or new timer arrives
  94. */
  95. for (;;) {
  96. // Pending and freelist maintenance
  97. SDL_LockSpinlock(&data->lock);
  98. {
  99. // Get any timers ready to be queued
  100. pending = data->pending;
  101. data->pending = NULL;
  102. // Make any unused timer structures available
  103. if (freelist_head) {
  104. freelist_tail->next = data->freelist;
  105. data->freelist = freelist_head;
  106. }
  107. }
  108. SDL_UnlockSpinlock(&data->lock);
  109. // Sort the pending timers into our list
  110. while (pending) {
  111. current = pending;
  112. pending = pending->next;
  113. SDL_AddTimerInternal(data, current);
  114. }
  115. freelist_head = NULL;
  116. freelist_tail = NULL;
  117. // Check to see if we're still running, after maintenance
  118. if (!SDL_GetAtomicInt(&data->active)) {
  119. break;
  120. }
  121. // Initial delay if there are no timers
  122. delay = (Uint64)-1;
  123. tick = SDL_GetTicksNS();
  124. // Process all the pending timers for this tick
  125. while (data->timers) {
  126. current = data->timers;
  127. if (tick < current->scheduled) {
  128. // Scheduled for the future, wait a bit
  129. delay = (current->scheduled - tick);
  130. break;
  131. }
  132. // We're going to do something with this timer
  133. data->timers = current->next;
  134. if (SDL_GetAtomicInt(&current->canceled)) {
  135. interval = 0;
  136. } else {
  137. if (current->callback_ms) {
  138. interval = SDL_MS_TO_NS(current->callback_ms(current->userdata, current->timerID, (Uint32)SDL_NS_TO_MS(current->interval)));
  139. } else {
  140. interval = current->callback_ns(current->userdata, current->timerID, current->interval);
  141. }
  142. }
  143. if (interval > 0) {
  144. // Reschedule this timer
  145. current->interval = interval;
  146. current->scheduled = tick + interval;
  147. SDL_AddTimerInternal(data, current);
  148. } else {
  149. if (!freelist_head) {
  150. freelist_head = current;
  151. }
  152. if (freelist_tail) {
  153. freelist_tail->next = current;
  154. }
  155. freelist_tail = current;
  156. SDL_SetAtomicInt(&current->canceled, 1);
  157. }
  158. }
  159. // Adjust the delay based on processing time
  160. now = SDL_GetTicksNS();
  161. interval = (now - tick);
  162. if (interval > delay) {
  163. delay = 0;
  164. } else {
  165. delay -= interval;
  166. }
  167. /* Note that each time a timer is added, this will return
  168. immediately, but we process the timers added all at once.
  169. That's okay, it just means we run through the loop a few
  170. extra times.
  171. */
  172. SDL_WaitSemaphoreTimeoutNS(data->sem, delay);
  173. }
  174. return 0;
  175. }
  176. bool SDL_InitTimers(void)
  177. {
  178. SDL_TimerData *data = &SDL_timer_data;
  179. if (!SDL_ShouldInit(&data->init)) {
  180. return true;
  181. }
  182. data->timermap_lock = SDL_CreateMutex();
  183. if (!data->timermap_lock) {
  184. goto error;
  185. }
  186. data->sem = SDL_CreateSemaphore(0);
  187. if (!data->sem) {
  188. goto error;
  189. }
  190. SDL_SetAtomicInt(&data->active, true);
  191. // Timer threads use a callback into the app, so we can't set a limited stack size here.
  192. data->thread = SDL_CreateThread(SDL_TimerThread, "SDLTimer", data);
  193. if (!data->thread) {
  194. goto error;
  195. }
  196. SDL_SetInitialized(&data->init, true);
  197. return true;
  198. error:
  199. SDL_SetInitialized(&data->init, true);
  200. SDL_QuitTimers();
  201. return false;
  202. }
  203. void SDL_QuitTimers(void)
  204. {
  205. SDL_TimerData *data = &SDL_timer_data;
  206. SDL_Timer *timer;
  207. SDL_TimerMap *entry;
  208. if (!SDL_ShouldQuit(&data->init)) {
  209. return;
  210. }
  211. SDL_SetAtomicInt(&data->active, false);
  212. // Shutdown the timer thread
  213. if (data->thread) {
  214. SDL_SignalSemaphore(data->sem);
  215. SDL_WaitThread(data->thread, NULL);
  216. data->thread = NULL;
  217. }
  218. if (data->sem) {
  219. SDL_DestroySemaphore(data->sem);
  220. data->sem = NULL;
  221. }
  222. // Clean up the timer entries
  223. while (data->timers) {
  224. timer = data->timers;
  225. data->timers = timer->next;
  226. SDL_free(timer);
  227. }
  228. while (data->freelist) {
  229. timer = data->freelist;
  230. data->freelist = timer->next;
  231. SDL_free(timer);
  232. }
  233. while (data->timermap) {
  234. entry = data->timermap;
  235. data->timermap = entry->next;
  236. SDL_free(entry);
  237. }
  238. if (data->timermap_lock) {
  239. SDL_DestroyMutex(data->timermap_lock);
  240. data->timermap_lock = NULL;
  241. }
  242. SDL_SetInitialized(&data->init, false);
  243. }
  244. static bool SDL_CheckInitTimers(void)
  245. {
  246. return SDL_InitTimers();
  247. }
  248. static SDL_TimerID SDL_CreateTimer(Uint64 interval, SDL_TimerCallback callback_ms, SDL_NSTimerCallback callback_ns, void *userdata)
  249. {
  250. SDL_TimerData *data = &SDL_timer_data;
  251. SDL_Timer *timer;
  252. SDL_TimerMap *entry;
  253. CHECK_PARAM(!callback_ms && !callback_ns) {
  254. SDL_InvalidParamError("callback");
  255. return 0;
  256. }
  257. if (!SDL_CheckInitTimers()) {
  258. return 0;
  259. }
  260. SDL_LockSpinlock(&data->lock);
  261. timer = data->freelist;
  262. if (timer) {
  263. data->freelist = timer->next;
  264. }
  265. SDL_UnlockSpinlock(&data->lock);
  266. if (timer) {
  267. SDL_RemoveTimer(timer->timerID);
  268. } else {
  269. timer = (SDL_Timer *)SDL_malloc(sizeof(*timer));
  270. if (!timer) {
  271. return 0;
  272. }
  273. }
  274. timer->timerID = SDL_GetNextObjectID();
  275. timer->callback_ms = callback_ms;
  276. timer->callback_ns = callback_ns;
  277. timer->userdata = userdata;
  278. timer->interval = interval;
  279. timer->scheduled = SDL_GetTicksNS() + timer->interval;
  280. SDL_SetAtomicInt(&timer->canceled, 0);
  281. entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry));
  282. if (!entry) {
  283. SDL_free(timer);
  284. return 0;
  285. }
  286. entry->timer = timer;
  287. entry->timerID = timer->timerID;
  288. SDL_LockMutex(data->timermap_lock);
  289. entry->next = data->timermap;
  290. data->timermap = entry;
  291. SDL_UnlockMutex(data->timermap_lock);
  292. // Add the timer to the pending list for the timer thread
  293. SDL_LockSpinlock(&data->lock);
  294. timer->next = data->pending;
  295. data->pending = timer;
  296. SDL_UnlockSpinlock(&data->lock);
  297. // Wake up the timer thread if necessary
  298. SDL_SignalSemaphore(data->sem);
  299. return entry->timerID;
  300. }
  301. SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *userdata)
  302. {
  303. return SDL_CreateTimer(SDL_MS_TO_NS(interval), callback, NULL, userdata);
  304. }
  305. SDL_TimerID SDL_AddTimerNS(Uint64 interval, SDL_NSTimerCallback callback, void *userdata)
  306. {
  307. return SDL_CreateTimer(interval, NULL, callback, userdata);
  308. }
  309. bool SDL_RemoveTimer(SDL_TimerID id)
  310. {
  311. SDL_TimerData *data = &SDL_timer_data;
  312. SDL_TimerMap *prev, *entry;
  313. bool canceled = false;
  314. CHECK_PARAM(!id) {
  315. return SDL_InvalidParamError("id");
  316. }
  317. // Find the timer
  318. SDL_LockMutex(data->timermap_lock);
  319. prev = NULL;
  320. for (entry = data->timermap; entry; prev = entry, entry = entry->next) {
  321. if (entry->timerID == id) {
  322. if (prev) {
  323. prev->next = entry->next;
  324. } else {
  325. data->timermap = entry->next;
  326. }
  327. break;
  328. }
  329. }
  330. SDL_UnlockMutex(data->timermap_lock);
  331. if (entry) {
  332. if (!SDL_GetAtomicInt(&entry->timer->canceled)) {
  333. SDL_SetAtomicInt(&entry->timer->canceled, 1);
  334. canceled = true;
  335. }
  336. SDL_free(entry);
  337. }
  338. if (canceled) {
  339. return true;
  340. } else {
  341. return SDL_SetError("Timer not found");
  342. }
  343. }
  344. #else // Emscripten-specific implementation.
  345. #include <emscripten/emscripten.h>
  346. #include <emscripten/eventloop.h>
  347. typedef struct SDL_TimerMap
  348. {
  349. SDL_TimerID timerID;
  350. int timeoutID;
  351. Uint64 interval;
  352. SDL_TimerCallback callback_ms;
  353. SDL_NSTimerCallback callback_ns;
  354. void *userdata;
  355. struct SDL_TimerMap *next;
  356. } SDL_TimerMap;
  357. typedef struct
  358. {
  359. SDL_TimerMap *timermap;
  360. } SDL_TimerData;
  361. static SDL_TimerData SDL_timer_data;
  362. static void SDL_Emscripten_TimerHelper(void *userdata)
  363. {
  364. SDL_TimerMap *entry = (SDL_TimerMap *)userdata;
  365. if (entry->callback_ms) {
  366. entry->interval = SDL_MS_TO_NS(entry->callback_ms(entry->userdata, entry->timerID, (Uint32)SDL_NS_TO_MS(entry->interval)));
  367. } else {
  368. entry->interval = entry->callback_ns(entry->userdata, entry->timerID, entry->interval);
  369. }
  370. if (entry->interval > 0) {
  371. entry->timeoutID = emscripten_set_timeout(&SDL_Emscripten_TimerHelper,
  372. SDL_NS_TO_MS(entry->interval),
  373. entry);
  374. }
  375. }
  376. bool SDL_InitTimers(void)
  377. {
  378. return true;
  379. }
  380. void SDL_QuitTimers(void)
  381. {
  382. SDL_TimerData *data = &SDL_timer_data;
  383. SDL_TimerMap *entry;
  384. while (data->timermap) {
  385. entry = data->timermap;
  386. data->timermap = entry->next;
  387. SDL_free(entry);
  388. }
  389. }
  390. static SDL_TimerID SDL_CreateTimer(Uint64 interval, SDL_TimerCallback callback_ms, SDL_NSTimerCallback callback_ns, void *userdata)
  391. {
  392. SDL_TimerData *data = &SDL_timer_data;
  393. SDL_TimerMap *entry;
  394. CHECK_PARAM(!callback_ms && !callback_ns) {
  395. SDL_InvalidParamError("callback");
  396. return 0;
  397. }
  398. entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry));
  399. if (!entry) {
  400. return 0;
  401. }
  402. entry->timerID = SDL_GetNextObjectID();
  403. entry->callback_ms = callback_ms;
  404. entry->callback_ns = callback_ns;
  405. entry->userdata = userdata;
  406. entry->interval = interval;
  407. entry->timeoutID = emscripten_set_timeout(&SDL_Emscripten_TimerHelper,
  408. SDL_NS_TO_MS(entry->interval),
  409. entry);
  410. entry->next = data->timermap;
  411. data->timermap = entry;
  412. return entry->timerID;
  413. }
  414. SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *userdata)
  415. {
  416. return SDL_CreateTimer(SDL_MS_TO_NS(interval), callback, NULL, userdata);
  417. }
  418. SDL_TimerID SDL_AddTimerNS(Uint64 interval, SDL_NSTimerCallback callback, void *userdata)
  419. {
  420. return SDL_CreateTimer(interval, NULL, callback, userdata);
  421. }
  422. bool SDL_RemoveTimer(SDL_TimerID id)
  423. {
  424. SDL_TimerData *data = &SDL_timer_data;
  425. SDL_TimerMap *prev, *entry;
  426. CHECK_PARAM(!id) {
  427. return SDL_InvalidParamError("id");
  428. }
  429. // Find the timer
  430. prev = NULL;
  431. for (entry = data->timermap; entry; prev = entry, entry = entry->next) {
  432. if (entry->timerID == id) {
  433. if (prev) {
  434. prev->next = entry->next;
  435. } else {
  436. data->timermap = entry->next;
  437. }
  438. break;
  439. }
  440. }
  441. if (entry) {
  442. emscripten_clear_timeout(entry->timeoutID);
  443. SDL_free(entry);
  444. return true;
  445. } else {
  446. return SDL_SetError("Timer not found");
  447. }
  448. }
  449. #endif // !SDL_PLATFORM_EMSCRIPTEN
  450. #ifdef USE_128BIT_MATH
  451. typedef unsigned __int128 Uint128;
  452. #endif
  453. static Uint64 tick_start;
  454. #ifdef USE_128BIT_MATH
  455. static Uint64 tick_numerator_ns;
  456. static Uint64 tick_numerator_ms;
  457. #else
  458. static Uint32 tick_numerator_ns;
  459. static Uint32 tick_denominator_ns;
  460. static Uint32 tick_numerator_ms;
  461. static Uint32 tick_denominator_ms;
  462. #endif
  463. #if defined(SDL_TIMER_WINDOWS) && !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  464. #include <mmsystem.h>
  465. #define HAVE_TIME_BEGIN_PERIOD
  466. #endif
  467. static void SDL_SetSystemTimerResolutionMS(int period)
  468. {
  469. #ifdef HAVE_TIME_BEGIN_PERIOD
  470. static int timer_period = 0;
  471. if (period != timer_period) {
  472. if (timer_period) {
  473. timeEndPeriod((UINT)timer_period);
  474. }
  475. timer_period = period;
  476. if (timer_period) {
  477. timeBeginPeriod((UINT)timer_period);
  478. }
  479. }
  480. #endif // HAVE_TIME_BEGIN_PERIOD
  481. }
  482. static void SDLCALL SDL_TimerResolutionChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  483. {
  484. int period;
  485. // Unless the hint says otherwise, let's have good sleep precision
  486. if (hint && *hint) {
  487. period = SDL_atoi(hint);
  488. } else {
  489. period = 1;
  490. }
  491. if (period || oldValue != hint) {
  492. SDL_SetSystemTimerResolutionMS(period);
  493. }
  494. }
  495. void SDL_InitTicks(void)
  496. {
  497. Uint64 tick_freq;
  498. #ifndef USE_128BIT_MATH
  499. Uint32 gcd;
  500. #endif
  501. if (tick_start) {
  502. return;
  503. }
  504. /* If we didn't set a precision, set it high. This affects lots of things
  505. on Windows besides the SDL timers, like audio callbacks, etc. */
  506. SDL_AddHintCallback(SDL_HINT_TIMER_RESOLUTION,
  507. SDL_TimerResolutionChanged, NULL);
  508. tick_freq = SDL_GetPerformanceFrequency();
  509. SDL_assert(tick_freq > 0 && tick_freq <= (Uint64)SDL_MAX_UINT32);
  510. #ifdef USE_128BIT_MATH
  511. tick_numerator_ns = ((Uint64)SDL_NS_PER_SECOND << 32) / tick_freq;
  512. tick_numerator_ms = ((Uint64)SDL_MS_PER_SECOND << 32) / tick_freq;
  513. #else
  514. gcd = SDL_CalculateGCD(SDL_NS_PER_SECOND, (Uint32)tick_freq);
  515. tick_numerator_ns = (SDL_NS_PER_SECOND / gcd);
  516. tick_denominator_ns = (Uint32)(tick_freq / gcd);
  517. gcd = SDL_CalculateGCD(SDL_MS_PER_SECOND, (Uint32)tick_freq);
  518. tick_numerator_ms = (SDL_MS_PER_SECOND / gcd);
  519. tick_denominator_ms = (Uint32)(tick_freq / gcd);
  520. #endif
  521. tick_start = SDL_GetPerformanceCounter();
  522. if (!tick_start) {
  523. --tick_start;
  524. }
  525. }
  526. void SDL_QuitTicks(void)
  527. {
  528. SDL_RemoveHintCallback(SDL_HINT_TIMER_RESOLUTION,
  529. SDL_TimerResolutionChanged, NULL);
  530. SDL_SetSystemTimerResolutionMS(0); // always release our timer resolution request.
  531. tick_start = 0;
  532. }
  533. Uint64 SDL_GetTicksNS(void)
  534. {
  535. Uint64 starting_value, value;
  536. if (!tick_start) {
  537. SDL_InitTicks();
  538. }
  539. starting_value = (SDL_GetPerformanceCounter() - tick_start);
  540. #ifdef USE_128BIT_MATH
  541. value = (Uint64)(((Uint128)starting_value * tick_numerator_ns) >> 32);
  542. #else
  543. value = (starting_value / tick_denominator_ns) * tick_numerator_ns +
  544. (starting_value % tick_denominator_ns) * tick_numerator_ns / tick_denominator_ns;
  545. #endif
  546. return value;
  547. }
  548. Uint64 SDL_GetTicks(void)
  549. {
  550. Uint64 starting_value, value;
  551. if (!tick_start) {
  552. SDL_InitTicks();
  553. }
  554. starting_value = (SDL_GetPerformanceCounter() - tick_start);
  555. #ifdef USE_128BIT_MATH
  556. value = (Uint64)(((Uint128)starting_value * tick_numerator_ms) >> 32);
  557. #else
  558. value = (starting_value / tick_denominator_ms) * tick_numerator_ms +
  559. (starting_value % tick_denominator_ms) * tick_numerator_ms / tick_denominator_ms;
  560. #endif
  561. return value;
  562. }
  563. void SDL_Delay(Uint32 ms)
  564. {
  565. SDL_SYS_DelayNS(SDL_MS_TO_NS(ms));
  566. }
  567. void SDL_DelayNS(Uint64 ns)
  568. {
  569. SDL_SYS_DelayNS(ns);
  570. }
  571. void SDL_DelayPrecise(Uint64 ns)
  572. {
  573. Uint64 current_value = SDL_GetTicksNS();
  574. const Uint64 target_value = current_value + ns;
  575. // Sleep for a short number of cycles when real sleeps are desired.
  576. // We'll use 1 ms, it's the minimum guaranteed to produce real sleeps across
  577. // all platforms.
  578. const Uint64 SHORT_SLEEP_NS = 1 * SDL_NS_PER_MS;
  579. // Try to sleep short of target_value. If for some crazy reason
  580. // a particular platform sleeps for less than 1 ms when 1 ms was requested,
  581. // that's fine, the code below can cope with that, but in practice no
  582. // platforms behave that way.
  583. Uint64 max_sleep_ns = SHORT_SLEEP_NS;
  584. while (current_value + max_sleep_ns < target_value) {
  585. // Sleep for a short time
  586. SDL_SYS_DelayNS(SHORT_SLEEP_NS);
  587. const Uint64 now = SDL_GetTicksNS();
  588. const Uint64 next_sleep_ns = (now - current_value);
  589. if (next_sleep_ns > max_sleep_ns) {
  590. max_sleep_ns = next_sleep_ns;
  591. }
  592. current_value = now;
  593. }
  594. // Do a shorter sleep of the remaining time here, less the max overshoot in
  595. // the first loop. Due to maintaining max_sleep_ns as
  596. // greater-than-or-equal-to-1 ms, we can always subtract off 1 ms to get
  597. // the duration overshot beyond a 1 ms sleep request; if the system never
  598. // overshot, great, it's zero duration. By choosing the max overshoot
  599. // amount, we're likely to not overshoot here. If the sleep here ends up
  600. // functioning like SDL_DelayNS(0) internally, that's fine, we just don't
  601. // get to do a more-precise-than-1 ms-resolution sleep to undershoot by a
  602. // small amount on the current system, but SDL_DelayNS(0) does at least
  603. // introduce a small, yielding delay on many platforms, better than an
  604. // unyielding busyloop.
  605. //
  606. // Note that we'll always do at least one sleep in this function, so the
  607. // minimum resolution will be that of SDL_SYS_DelayNS()
  608. if (current_value < target_value && (target_value - current_value) > (max_sleep_ns - SHORT_SLEEP_NS)) {
  609. const Uint64 delay_ns = (target_value - current_value) - (max_sleep_ns - SHORT_SLEEP_NS);
  610. SDL_SYS_DelayNS(delay_ns);
  611. current_value = SDL_GetTicksNS();
  612. }
  613. // We've likely undershot target_value at this point by a pretty small
  614. // amount, but maybe not. The footgun case if not handled here is where
  615. // we've undershot by a large amount, like several ms, but still smaller
  616. // than the amount max_sleep_ns overshot by; in such a situation, the above
  617. // shorter-sleep block didn't do any delay, the if-block wasn't entered.
  618. // Also, maybe the shorter-sleep undershot by several ms, so we still don't
  619. // want to spin a lot then. In such a case, we accept the possibility of
  620. // overshooting to not spin much, or if overshot here, not at all, keeping
  621. // CPU/power usage down in any case. Due to scheduler sloppiness, it's
  622. // entirely possible to end up undershooting/overshooting here by much less
  623. // than 1 ms even if the current system's sleep function is only 1
  624. // ms-resolution, as SDL_GetTicksNS() generally is better resolution than 1
  625. // ms on the systems SDL supports.
  626. while (current_value + SHORT_SLEEP_NS < target_value) {
  627. SDL_SYS_DelayNS(SHORT_SLEEP_NS);
  628. current_value = SDL_GetTicksNS();
  629. }
  630. // Spin for any remaining time
  631. while (current_value < target_value) {
  632. SDL_CPUPauseInstruction();
  633. current_value = SDL_GetTicksNS();
  634. }
  635. }