DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
MeasureCPU
// Scala code for micro-benchmarking.
package speed;
object fun {
val mf = java.lang.management.ManagementFactory.getThreadMXBean
assert (mf.isCurrentThreadCpuTimeSupported)
mf.setThreadCpuTimeEnabled (true)
/**
* Run fun
for some time and return <i>operations per second</i>.<br>
* The time is measured using thread CPU time counter.
*/
def measureCPU (fun: => Unit) (implicit seconds: Double) = {
var left = 99; while (left != 0) {left -= 1; fun} // Warm-up cycle.
val t1 = mf.getCurrentThreadCpuTime; var t2 = t1; var count = 0
do {
var left = 999; count += left; while (left != 0) {left -= 1; fun}
t2 = mf.getCurrentThreadCpuTime
} while (t2 - t1 < seconds * 1000000000)
(count.toDouble / (t2 - t1) * 1000000000).toInt + " o/s"
}
}





