Scoop API

scoop:scoop.platform:0.1.0

src/time/clocks.scoop

Selected production source · src/time/clocks.scoop

1package scoop.platform.time
3import scoop.platform.system.failOperatingSystem
4import scoop.time.*
6/**
7 * The operating-system wall clock used for civil timestamps; it can change when system time is
8 * adjusted.
9 */
10public object SystemClock: Clock {
11 /**
12 * Reads the current wall-clock instant.
13 */
14 public override fun now(): Instant {
15 val value = readClock(false)
16 return Instant.fromEpochSeconds(value.seconds, value.nanoseconds)
17 }
20/**
21 * A monotonic source for elapsed-time measurement, independent of wall-clock adjustments.
22 */
23public object MonotonicTimeSource: TimeSource {
24 /** Captures the fixed system clock as a reference-free timestamp. */
25 public fun now(): MonotonicInstant {
26 val value = readClock(true)
27 return MonotonicInstant(value.seconds, value.nanoseconds.toInt())
28 }
30 /**
31 * Captures a monotonic time mark.
32 */
33 public override fun markNow(): TimeMark {
34 return TimeMark(this, now().reading())
35 }
38/**
39 * Blocks the current native thread for a nonnegative duration.
40 */
41public fun sleep(duration: Duration) {
42 if (duration.floorSeconds < 0L)
43 throw IllegalArgumentException(Some("negative sleep duration"))
44 if (duration == Duration.ZERO)
45 return
46 @Unsafe
47 {
48 val error = nativeSleep(duration.floorSeconds, duration.nanosecondsOfSecond)
49 if (error != 0)
50 failOperatingSystem("sleep", error)
51 }
54/**
55 * Measures elapsed monotonic time since this mark.
56 */
57public fun TimeMark.elapsedNow(): Duration = source.markNow() - this
59/**
60 * A returned value paired with the duration measured while producing it.
61 */
62public struct TimedValue<T>(val value: T, val duration: Duration)
64/**
65 * Runs the block and measures its elapsed duration using the selected source.
66 */
67public fun measureTime(source: TimeSource = MonotonicTimeSource, block: () -> Unit): Duration {
68 val start = source.markNow()
69 block()
70 return source.markNow() - start
73/**
74 * Runs the block and returns both its result and measured elapsed duration.
75 */
76public fun <T> measureTimedValue(
77 source: TimeSource = MonotonicTimeSource,
78 block: () -> T
79): TimedValue<T> {
80 val start = source.markNow()
81 val value = block()
82 return TimedValue(value, source.markNow() - start)
85@CLayout
86private struct NativeTime(val seconds: Long, val nanoseconds: Long, val error: Int)
88private fun readClock(monotonic: Boolean): NativeTime {
89 @Unsafe
90 {
91 val value = nativeClock(monotonic)
92 if (value.error != 0)
93 failOperatingSystem("clock read", value.error)
94 return value
95 }
98@GCLeaf
99@Extern(name = "scoop_platform_clock")
100private fun nativeClock(monotonic: Boolean): NativeTime
102@Extern(name = "scoop_platform_sleep")
103private fun nativeSleep(seconds: Long, nanoseconds: Int): Int