diff --git a/libraries/stdlib/jvm/src/kotlin/system/Timing.kt b/libraries/stdlib/jvm/src/kotlin/system/Timing.kt index b4cfdef8bee..2e425cae1ec 100644 --- a/libraries/stdlib/jvm/src/kotlin/system/Timing.kt +++ b/libraries/stdlib/jvm/src/kotlin/system/Timing.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -10,6 +10,8 @@ import kotlin.contracts.* /** * Executes the given [block] and returns elapsed time in milliseconds. + * + * @sample samples.system.Timing.measureBlockTimeMillis */ public inline fun measureTimeMillis(block: () -> Unit): Long { contract { @@ -22,6 +24,8 @@ public inline fun measureTimeMillis(block: () -> Unit): Long { /** * Executes the given [block] and returns elapsed time in nanoseconds. + * + * @sample samples.system.Timing.measureBlockNanoTime */ public inline fun measureNanoTime(block: () -> Unit): Long { contract { diff --git a/libraries/stdlib/samples/test/samples/system/timing.kt b/libraries/stdlib/samples/test/samples/system/timing.kt new file mode 100644 index 00000000000..62d51c8450b --- /dev/null +++ b/libraries/stdlib/samples/test/samples/system/timing.kt @@ -0,0 +1,39 @@ +/* + * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. + */ + +package samples.system + +import samples.* +import kotlin.system.* + +class Timing { + + @Sample + fun measureBlockTimeMillis() { + val numbers: List + val timeInMillis = measureTimeMillis { + numbers = buildList { + addAll(0..100) + shuffle() + sortDescending() + } + } + // here numbers are initialized and sorted + assertPrints(numbers.first(), "100") + + println("(The operation took $timeInMillis ms)") + } + + @Sample + fun measureBlockNanoTime() { + var sqrt = 0 + val number = 1000 + val timeInNanos = measureNanoTime { + while (sqrt * sqrt < number) sqrt++ + } + println("(The operation took $timeInNanos ns)") + println("The approximate square root of $number is between ${sqrt - 1} and $sqrt") + } +}