Skip to content

Instantly share code, notes, and snippets.

@TJC
Last active August 29, 2022 08:10
Show Gist options
  • Save TJC/1eea4f628476ee9283afcdbb0956546e to your computer and use it in GitHub Desktop.
Save TJC/1eea4f628476ee9283afcdbb0956546e to your computer and use it in GitHub Desktop.
Benchmark ways of getting the time as seconds (Scala/Java)
import java.time.Clock
import java.time.Instant
object BenchTime {
val clock = Clock.systemUTC
def bench(fn: () => Unit, iterations: Int = 1000000) = {
val start = System.nanoTime
Range(0,iterations).foreach( _ => fn() )
val end = System.nanoTime
val millis = (end - start) / 1000000.0
millis
}
def medianBench(title: String, fn: () => Unit) = {
System.gc()
Thread.sleep(500)
val results = Range(0,10).map( _ => bench(fn))
val median = results.sorted.apply(5)
println(s"$median ms\t$title")
}
// Things to benchmark:
def systemTime(): Unit = {
val t = System.currentTimeMillis() / 1000
}
def clockTimeMillis(): Unit = {
val t = clock.millis() / 1000
}
def clockTimeInstant(): Unit = {
val t = clock.instant.getEpochSecond()
}
def instantNow(): Unit = {
val t = Instant.now().getEpochSecond()
}
def main(args: Array[String]): Unit = {
// Warm up the JIT with initial passes..
bench(systemTime)
bench(clockTimeMillis)
bench(clockTimeInstant)
bench(instantNow)
medianBench("System.currentTimeMillis()", systemTime)
medianBench("clock.millis()", clockTimeMillis)
medianBench("clock.instant.getEpochSecond()", clockTimeInstant)
medianBench("Instant.now().getEpochSecond()", instantNow)
// Reverse order to verify
medianBench("Instant.now().getEpochSecond()", instantNow)
medianBench("clock.instant.getEpochSecond()", clockTimeInstant)
medianBench("clock.millis()", clockTimeMillis)
medianBench("System.currentTimeMillis()", systemTime)
}
}
@TJC
Copy link
Author

TJC commented Aug 29, 2022

The results I get are:

17.578916 ms	System.currentTimeMillis() / 1000
17.284542 ms	clock.millis() / 1000
67.385 ms	clock.instant.getEpochSecond()
68.379417 ms	Instant.now().getEpochSecond()
67.518042 ms	Instant.now().getEpochSecond()
67.609458 ms	clock.instant.getEpochSecond()
17.327542 ms	clock.millis() / 1000
17.311 ms	System.currentTimeMillis() / 1000

(These are time elapsed for a million iterations, so the actual time-per-call is n/1000000)

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