Skip to content

Instantly share code, notes, and snippets.

@JoshRosen
Created October 21, 2021 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshRosen/d49213f0bcb62de6dbbe039746a7740d to your computer and use it in GitHub Desktop.
Save JoshRosen/d49213f0bcb62de6dbbe039746a7740d to your computer and use it in GitHub Desktop.
toy benchmark of OpenHashMap
def timeAndRecordAllocations(
numWarmups: Int,
numTrials: Int
)(functionToBenchmark: => Unit): Unit = {
import java.lang.management.ManagementFactory
import com.sun.management.ThreadMXBean
val threadMxBean = ManagementFactory.getThreadMXBean.asInstanceOf[ThreadMXBean]
val threadId = Thread.currentThread.getId
// Warmup:
{
var i = 0
while (i < numWarmups) {
functionToBenchmark
i += 1
}
}
// Benchmark:
System.gc()
val bytesBefore = threadMxBean.getThreadAllocatedBytes(threadId)
val cpuTimeBefore = threadMxBean.getThreadCpuTime(threadId)
{
var i = 0
while (i < numTrials) {
functionToBenchmark
i += 1
}
}
val cpuTimeAfter = threadMxBean.getThreadCpuTime(threadId)
System.gc()
val bytesAfter = threadMxBean.getThreadAllocatedBytes(threadId)
// scalastyle:off
println(s"Estimated: ${bytesAfter - bytesBefore}")
println(s"CPU time: ${cpuTimeAfter - cpuTimeBefore}")
}
test("benchmark") {
timeAndRecordAllocations(10, 10) {
val map = new OpenHashMap[Int, Int]
var i = 0
while (i < 10000000) {
map(i) = i
i += 1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment