Last active
August 29, 2022 08:10
-
-
Save TJC/1eea4f628476ee9283afcdbb0956546e to your computer and use it in GitHub Desktop.
Benchmark ways of getting the time as seconds (Scala/Java)
This file contains hidden or 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.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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The results I get are:
(These are time elapsed for a million iterations, so the actual time-per-call is
n/1000000
)