Last active
August 15, 2020 02:28
-
-
Save Elvis10ten/764bf5704f7265f7ff7812e5588dd93d to your computer and use it in GitHub Desktop.
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.math.abs | |
typealias Duration = Long | |
typealias Sample = Long | |
object ThreadSleepStats { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
val durations = listOf(1L, 10L, 100L, 1000L) | |
val durationSamples = mutableMapOf<Duration, MutableList<Sample>>() | |
val numSamples = 100 | |
for(sampleIndex in 0 until numSamples) { | |
for(duration in durations) { | |
val startTime = System.nanoTime() | |
Thread.sleep(duration) | |
val endTime = System.nanoTime() | |
val timeDiff = endTime - startTime | |
val samples = durationSamples.getOrDefault(duration, mutableListOf()) | |
samples += timeDiff | |
durationSamples[duration] = samples | |
} | |
} | |
for((duration, samples) in durationSamples) { | |
val summedSamples = samples.sum() | |
val mean = nanoToMillis(summedSamples) / numSamples | |
val mad = (samples.fold(0.0) { acc, sample -> acc + abs((nanoToMillis(sample) - mean)) }) / numSamples | |
val meanFormatted = String.format("%.6f", mean) | |
val madFormatted = String.format("%.6f", mad) | |
println("Sleep($duration ms) stats:") | |
println("Mean: ${meanFormatted}ms") | |
println("Mean Absolute Deviation (MAD): ${madFormatted}ms\n") | |
} | |
} | |
/* | |
Can't use TimeUnit as values are truncated going from finer to coarser granularity | |
*/ | |
private fun nanoToMillis(nanoTime: Long): Double | |
= nanoTime / 1E6 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment