Selaa lähdekoodia

libobs/util: Add os_sleepto_ns_fast

The function `os_sleepto_ns` has a spin loop so it will consume CPU
resource. The new function has same interface but consumes less CPU
resource with a drawback of less precision.
Norihiro Kamae 3 vuotta sitten
vanhempi
sitoutus
c491594a51

+ 7 - 0
docs/sphinx/reference-libobs-util-platform.rst

@@ -194,6 +194,13 @@ Sleep/Time Functions
 
 
 ---------------------
 ---------------------
 
 
+.. function:: bool os_sleepto_ns_fast(uint64_t time_target)
+
+   Sleeps to a specific time without high precision, in nanoseconds.
+   The function won't return until reaching the specific time.
+
+---------------------
+
 .. function:: void os_sleep_ms(uint32_t duration)
 .. function:: void os_sleep_ms(uint32_t duration)
 
 
    Sleeps for a specific number of milliseconds.
    Sleeps for a specific number of milliseconds.

+ 17 - 0
libobs/util/platform-nix.c

@@ -180,6 +180,23 @@ bool os_sleepto_ns(uint64_t time_target)
 	return true;
 	return true;
 }
 }
 
 
+bool os_sleepto_ns_fast(uint64_t time_target)
+{
+	uint64_t current = os_gettime_ns();
+	if (time_target < current)
+		return false;
+
+	do {
+		uint64_t remain_us = (time_target - current + 999) / 1000;
+		useconds_t us = remain_us >= 1000000 ? 999999 : remain_us;
+		usleep(us);
+
+		current = os_gettime_ns();
+	} while (time_target > current);
+
+	return true;
+}
+
 void os_sleep_ms(uint32_t duration)
 void os_sleep_ms(uint32_t duration)
 {
 {
 	usleep(duration * 1000);
 	usleep(duration * 1000);

+ 18 - 0
libobs/util/platform-windows.c

@@ -360,6 +360,24 @@ bool os_sleepto_ns(uint64_t time_target)
 	return stall;
 	return stall;
 }
 }
 
 
+bool os_sleepto_ns_fast(uint64_t time_target)
+{
+	uint64_t current = os_gettime_ns();
+	if (time_target < current)
+		return false;
+
+	do {
+		uint64_t remain_ms = (time_target - current) / 1000000;
+		if (!remain_ms)
+			remain_ms = 1;
+		Sleep((DWORD)remain_ms);
+
+		current = os_gettime_ns();
+	} while (time_target > current);
+
+	return true;
+}
+
 void os_sleep_ms(uint32_t duration)
 void os_sleep_ms(uint32_t duration)
 {
 {
 	/* windows 8+ appears to have decreased sleep precision */
 	/* windows 8+ appears to have decreased sleep precision */

+ 1 - 0
libobs/util/platform.h

@@ -103,6 +103,7 @@ EXPORT void os_end_high_performance(os_performance_token_t *);
  * Returns false if already at or past target time.
  * Returns false if already at or past target time.
  */
  */
 EXPORT bool os_sleepto_ns(uint64_t time_target);
 EXPORT bool os_sleepto_ns(uint64_t time_target);
+EXPORT bool os_sleepto_ns_fast(uint64_t time_target);
 EXPORT void os_sleep_ms(uint32_t duration);
 EXPORT void os_sleep_ms(uint32_t duration);
 
 
 EXPORT uint64_t os_gettime_ns(void);
 EXPORT uint64_t os_gettime_ns(void);