Skip to content

Commit 637c0c8

Browse files
author
Abduqodiri Qurbonzoda
committed
Use kotlin.time API instead of kotlin.system.getTimeNanos()
1 parent 5d1c909 commit 637c0c8

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

runtime/nativeMain/src/kotlinx/benchmark/native/NativeExecutor.kt

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package kotlinx.benchmark.native
22

33
import kotlinx.benchmark.*
44
import kotlin.native.internal.GC
5-
import kotlin.system.*
5+
import kotlin.time.*
66

77
class NativeExecutor(
88
name: String,
@@ -218,25 +218,28 @@ class NativeExecutor(
218218
return getStackTrace().joinToString("\n") + "\nCause: ${nested.message}\n" + nested.stacktrace()
219219
}
220220

221+
@OptIn(ExperimentalTime::class)
221222
private inline fun measure(
222223
cycles: Int,
223224
nativeGCAfterIteration: Boolean,
224225
body: () -> Unit,
225226
): Double {
226-
var counter = cycles
227227
if (nativeGCAfterIteration)
228228
GC.collect()
229-
val startTime = getTimeNanos()
230-
while (counter-- > 0) {
231-
body()
229+
230+
val duration = measureTime {
231+
var counter = cycles
232+
while (counter-- > 0) {
233+
body()
234+
}
235+
if (nativeGCAfterIteration)
236+
GC.collect()
232237
}
233-
if (nativeGCAfterIteration)
234-
GC.collect()
235-
val endTime = getTimeNanos()
236-
val time = endTime - startTime
237-
return time.toDouble() / cycles
238+
239+
return duration.toDouble(DurationUnit.NANOSECONDS) / cycles
238240
}
239241

242+
@OptIn(ExperimentalTime::class)
240243
private inline fun <T> measureWarmup(
241244
name: String,
242245
config: BenchmarkConfiguration,
@@ -256,19 +259,18 @@ class NativeExecutor(
256259

257260
if (config.nativeGCAfterIteration)
258261
GC.collect()
259-
val startTime = getTimeNanos()
260-
var endTime = startTime
262+
val startTime = TimeSource.Monotonic.markNow()
263+
var duration = Duration.ZERO
261264
iterations = 0
262-
while (endTime - startTime < benchmarkNanos) {
265+
while (duration.inWholeNanoseconds < benchmarkNanos) {
263266
body()
264-
endTime = getTimeNanos()
267+
duration = startTime.elapsedNow()
265268
iterations++
266269
}
267270
if (config.nativeGCAfterIteration)
268271
GC.collect()
269272

270-
val time = endTime - startTime
271-
val metric = time.toDouble() / iterations // TODO: metric
273+
val metric = duration.toDouble(DurationUnit.NANOSECONDS) / iterations // TODO: metric
272274
val sample = metric.nanosToText(config.mode, config.outputTimeUnit)
273275
val iterationNumber = currentIteration ?: iteration
274276
reporter.output(name, benchmark.name, "Warm-up #$iterationNumber: $sample")

0 commit comments

Comments
 (0)