Added samples for the kotlin.system package (measureTime* functions)

Co-authored-by: Ilya Gorbunov <ilya.gorbunov@jetbrains.com>
This commit is contained in:
Uzi Landsmann
2020-10-01 23:04:53 +02:00
committed by Ilya Gorbunov
parent 15381c4662
commit f48f7c6dca
2 changed files with 44 additions and 1 deletions
@@ -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 {
@@ -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<Int>
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")
}
}