Skip to content

Commit

Permalink
Fix preciseDelay: delay() is proven to be inaccurate upto 2ms (#5173)
Browse files Browse the repository at this point in the history
Noticed that in preciseDelay we may spent more than 1.5ms to expected.
  • Loading branch information
pjBooms authored Dec 5, 2024
1 parent 6638b21 commit f999cb0
Showing 1 changed file with 7 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Expand Down

0 comments on commit f999cb0

Please sign in to comment.