Skip to content

Instantly share code, notes, and snippets.

@jrenner
Created September 20, 2014 05:11
Show Gist options
  • Save jrenner/0541cbd09b4488463858 to your computer and use it in GitHub Desktop.
Save jrenner/0541cbd09b4488463858 to your computer and use it in GitHub Desktop.
Expressive Kotlin
package org.jrenner.tactical.utils
import com.badlogic.gdx.utils.TimeUtils
object Timer {
enum class TimeUnit(val name: String) {
Seconds : TimeUnit("seconds")
Millis : TimeUnit("millis")
Micros : TimeUnit("micros")
Nanos : TimeUnit("nanos")
fun humanTime(nanoTime: Long): String {
val mult = when (this) {
Seconds -> 1 / 1000000000f
Millis -> 1 / 1000000f
Micros -> 1 / 1000f
Nanos -> 1f
}
val precision = when (this) {
Seconds -> "2"
else -> "0"
}
return "%.${precision}f ${name}".format(nanoTime.toFloat() * mult)
}
}
fun measure(func: () -> Unit, name: String = "timer") {
val start = TimeUtils.nanoTime()
func()
val time = TimeUtils.timeSinceNanos(start)
println("[timer: $name]: ${TimeUnit.Millis.humanTime(time)}")
}
fun example() {
val myFunc = { for (i in 1..1000) println("hello") }
Timer.measure(myFunc, "hello printer")
// output: [timer: hello printer]: 33 millis
}
}
@apatrida
Copy link

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