Created
June 7, 2010 12:33
-
-
Save ussy/428617 to your computer and use it in GitHub Desktop.
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
object Benchmark { | |
import java.lang.management.ManagementFactory | |
val CAPTION = " user system total real" | |
def benchmark(block: Job => Unit) : Unit = benchmark(1)(block) | |
def benchmark(count: Int)(block: Job => Unit) : Unit = { | |
val job = new Job(count) | |
block(job) | |
job.dump() | |
} | |
def measure(block: => Unit) = { | |
val start = now | |
block | |
val end = now | |
new Result( | |
(end._1 - start._1) / 1000000000, | |
(end._2 - start._2) / 1000000000, | |
(end._3 - start._3) / 1000 | |
) | |
} | |
private def now = { | |
val mx = ManagementFactory.getThreadMXBean() | |
val userTime = mx.getCurrentThreadUserTime() | |
val systemTime = mx.getCurrentThreadCpuTime() - mx.getCurrentThreadUserTime() | |
(userTime, systemTime, System.currentTimeMillis()) | |
} | |
} | |
class Result(val user: Double, val system: Double, val real: Double) { | |
val total = user + system | |
def +(result: Result) = new Result( | |
this.user + result.user, | |
this.system + result.system, | |
this.real + result.real | |
) | |
def format(count: Int) = "%9.4f %9.4f %9.4f %9.4f %9.4f/s (n=%d)".format( | |
user, | |
system, | |
total, | |
real, | |
count / total, | |
count) | |
override def toString() = format(1) | |
} | |
class Job(count: Int = 1) { | |
private var results = List[(String, Result)]() | |
var captionLength: Int = _ | |
def dump() { | |
println("%s %s".format(" " * captionLength, Benchmark.CAPTION)) | |
results.foreach { case (label, result) => | |
println("%s%s %s".format(" " * (captionLength - label.length), label, result.format(count))) | |
} | |
} | |
def report(block: => Unit) : Unit = report("")(block) | |
def report(label: String = "")(block: => Unit) : Unit = { | |
if (captionLength < label.length) captionLength = label.length | |
var sum = new Result(0, 0, 0) | |
(0 until count).foreach {i => | |
val result = Benchmark.measure(block) | |
sum = sum + result | |
} | |
results = results :+ (label, sum) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment