Skip to content

Instantly share code, notes, and snippets.

@kenilt
Last active November 30, 2018 07:55
Show Gist options
  • Save kenilt/160bbdfb72c6d6a2095b672be5ca33ae to your computer and use it in GitHub Desktop.
Save kenilt/160bbdfb72c6d6a2095b672be5ca33ae to your computer and use it in GitHub Desktop.
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.*
abstract class Benchmark(internal val name: String) {
@Throws(Throwable::class)
internal abstract fun run(iterations: Int)
private fun time(): BigDecimal {
try {
var nextI = 1
var i: Int
var duration: Long
do {
i = nextI
val start = System.nanoTime()
run(i)
duration = System.nanoTime() - start
nextI = i shl 1 or 1
} while (duration < 100000000 && nextI > 0)
return BigDecimal(duration * 1000 / i).movePointLeft(3)
} catch (e: Throwable) {
throw RuntimeException(e)
}
}
override fun toString(): String {
return name + "\t" + time() + " ns"
}
companion object {
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
val format = "dd/MM/yyy HH:mm:ss"
val benchmarks = arrayOf(object : Benchmark("One instance") {
@Throws(Throwable::class)
override fun run(iterations: Int) {
val dateFormat = SimpleDateFormat(format, Locale.US)
for (i in 0 until iterations) {
dateFormat.format(Date())
}
}
}, object : Benchmark("Multiple instances") {
@Throws(Throwable::class)
override fun run(iterations: Int) {
for (i in 0 until iterations) {
val dateFormat = SimpleDateFormat(format, Locale.US)
dateFormat.format(Date())
}
}
})
for (bm in benchmarks) {
println(bm)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment