Last active
October 5, 2017 11:42
-
-
Save canni/edfd680de012b544d5094d1164594365 to your computer and use it in GitHub Desktop.
Go like benchmark function for Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlin.system.measureTimeMillis | |
fun benchmarkIt(msg: String, block: (Int) -> Unit) { | |
var n = 1 | |
var duration: Long | |
do { | |
duration = measureTimeMillis { repeat(n, block) } | |
n *= 2 | |
} while (duration < 100L) | |
val nsPerOp = duration.toDouble() * 1000 / n.toDouble() | |
println( | |
"%s ran %d operations in %d milliseconds; avg: %.3f ns/op".format( | |
msg, n, duration, nsPerOp | |
) | |
) | |
} | |
// Outputs (on my machine): | |
// String interpolation ran 8388608 operations in 191 milliseconds; avg: 0.023 ns/op | |
// String concatenation ran 8388608 operations in 172 milliseconds; avg: 0.021 ns/op | |
fun main(args: Array<String>) { | |
benchmarkIt("String interpolation") { | |
"String $it interpolation" | |
} | |
benchmarkIt("String concatenation") { | |
"String " + it + " concatenation" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment