Created
October 21, 2021 21:34
-
-
Save JoshRosen/d49213f0bcb62de6dbbe039746a7740d to your computer and use it in GitHub Desktop.
toy benchmark of OpenHashMap
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
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