From f999cb09fe47ce861ce5c7b04e0fae06a3f81434 Mon Sep 17 00:00:00 2001 From: Nikita Lipsky Date: Thu, 5 Dec 2024 11:34:18 +0200 Subject: [PATCH] Fix preciseDelay: delay() is proven to be inaccurate upto 2ms (#5173) Noticed that in preciseDelay we may spent more than 1.5ms to expected. --- .../src/commonMain/kotlin/MeasureComposable.kt | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/benchmarks/multiplatform/src/commonMain/kotlin/MeasureComposable.kt b/benchmarks/multiplatform/src/commonMain/kotlin/MeasureComposable.kt index 6441e42bac..409a8f772a 100644 --- a/benchmarks/multiplatform/src/commonMain/kotlin/MeasureComposable.kt +++ b/benchmarks/multiplatform/src/commonMain/kotlin/MeasureComposable.kt @@ -8,7 +8,6 @@ import kotlin.time.Duration import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.ExperimentalTime import kotlinx.coroutines.* -import kotlin.time.Duration.Companion.milliseconds import kotlin.time.TimeSource.Monotonic.markNow import kotlin.time.measureTime @@ -24,15 +23,17 @@ expect fun runGC() suspend inline fun preciseDelay(duration: Duration) { val liveDelay: Duration - if (duration.inWholeMilliseconds > 1) { - val delayMillis = duration.inWholeMilliseconds - 1 + if (duration.inWholeMilliseconds > 2) { + //experiments have shown that for precise delay we should do live delay at least 2 ms + val delayMillis = duration.inWholeMilliseconds - 2 + val delayStart = markNow() delay(delayMillis) - liveDelay = duration - delayMillis.milliseconds + liveDelay = duration - delayStart.elapsedNow() } else { liveDelay = duration } - val start = markNow() - while (start.elapsedNow() < liveDelay){} + val liveDelayStart = markNow() + while (liveDelayStart.elapsedNow() < liveDelay){} } @OptIn(ExperimentalTime::class, InternalComposeUiApi::class)