Created
September 20, 2014 05:11
-
-
Save jrenner/0541cbd09b4488463858 to your computer and use it in GitHub Desktop.
Expressive Kotlin
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
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or other ways to play with this:
https://gist.github.com/jaysonminard/a496cc60416c01044628