Skip to content

Instantly share code, notes, and snippets.

@azabost
Created February 6, 2018 22:58
Show Gist options
  • Save azabost/bbd75cd9043d5f9a1e2cdc8cb232257a to your computer and use it in GitHub Desktop.
Save azabost/bbd75cd9043d5f9a1e2cdc8cb232257a to your computer and use it in GitHub Desktop.
Kotlin nanoTime granularity tests
package com.azabost.benchmarks.granularity
interface GranularityTester {
val measurements: Int
fun start()
}
package com.azabost.benchmarks.granularity
import com.azabost.benchmarks.utils.logger
fun GranularityTester.logDiffs(list: List<Long>, description: String) {
val log = logger
val sortedList = list.sorted()
val avg = list.average()
val median = if (sortedList.size % 2 == 0) {
val middleLeft = sortedList[sortedList.lastIndex / 2]
val middleRight = sortedList[sortedList.size / 2]
(middleLeft + middleRight) / 2
} else {
sortedList[sortedList.lastIndex / 2]
}
val min = sortedList.first()
val max = sortedList.last()
log.info("$description: min: $min, max: $max, avg: $avg, median: $median")
}
package com.azabost.benchmarks.granularity
import com.azabost.benchmarks.utils.logger
class KotlinGranularityTester(override val measurements: Int = 1000000) : GranularityTester {
private val log = logger
override fun start() {
log.info("Starting Kotlin granularity test")
log.info("Measuring no operation diffs")
val noOpDiffs = mutableListOf<Long>()
for (i in 0 until measurements) {
val noOpBegin = System.nanoTime()
val noOpEnd = System.nanoTime()
val noOpDiff = Math.abs(noOpEnd - noOpBegin)
noOpDiffs += noOpDiff
}
log.info("Measuring addConst function calls diffs")
val addConstFuncDiffs = mutableListOf<Long>()
var sum = 0L
for (i in 0 until measurements) {
val callFuncBegin = System.nanoTime()
sum += addConst(1)
val callFuncEnd = System.nanoTime()
val callFuncDiff = Math.abs(callFuncEnd - callFuncBegin)
addConstFuncDiffs += callFuncDiff
}
log.debug("sum: {}", sum)
log.info("Measuring nanoTime() diffs")
val nanoTimeDiffs = mutableListOf<Long>()
var nanoSum = 0L
for (i in 0 until measurements) {
val nanoBegin = System.nanoTime()
nanoSum += System.nanoTime()
val nanoEnd = System.nanoTime()
val nanoDiff = Math.abs(nanoEnd - nanoBegin)
nanoTimeDiffs += nanoDiff
}
log.debug("nanoSum: {}", nanoSum)
logDiffs(noOpDiffs, "No operation diffs")
logDiffs(addConstFuncDiffs, "addConst function call diffs")
logDiffs(nanoTimeDiffs, "nanoTime() diffs")
}
private fun addConst(a: Long): Long {
return a + 5
}
}
@azabost
Copy link
Author

azabost commented Feb 6, 2018

No operation diffs: min: 1406, max: 311354, avg: 1563.217939, median: 1511
addConst function call diffs: min: 2395, max: 153229, avg: 2562.990341, median: 2500
nanoTime() diffs: min: 2760, max: 1405000, avg: 2977.978546, median: 2917

Much longer (~100x) than using Spanner.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment