Last active
November 30, 2018 07:55
-
-
Save kenilt/160bbdfb72c6d6a2095b672be5ca33ae 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 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