Skip to content

Instantly share code, notes, and snippets.

@Sciss
Created July 24, 2012 15:00
Show Gist options
  • Save Sciss/3170504 to your computer and use it in GitHub Desktop.
Save Sciss/3170504 to your computer and use it in GitHub Desktop.
Bench1.scala
package benchmark
object Bench1 extends App {
def time(f: => Unit) = {
val start = System.nanoTime()
f
System.nanoTime() - start
}
def whileBenchmark1(times: Int) = {
time {
var i,j,k = 0
var x: Any = null
while(i < times) {
while(j < 1000) {
while(k < 1000) {
x = new Object()
k += 1
}
k = 0
j += 1
}
j = 0
i += 1
}
}
}
def whileBenchmark2(times: Int) = {
time {
var i,j,k = 0
var x = 0L
while(i < times) {
while(j < 1000) {
while(k < 1000) {
x += 1
k += 1
}
k = 0
j += 1
}
j = 0
i += 1
}
}
}
def forBenchmark1(times: Int) = {
time{
var obj: Any = null
for(i <- 0 until times; j <- 0 until 1000; k <- 0 until 1000)
obj = new Object
}
}
def forBenchmark2(times: Int) = {
time{
var x: Long = 0
for(i <- 0 until times; j <- 0 until 1000; k <- 0 until 1000)
x += 1
}
}
def test(name: String, bench: Int => Long) {
println(name + " took " + bench(10000)/10000000.0 + " µs per run" )
}
println( "Running benchmarks for n = " + 1000 )
test("while1", whileBenchmark1 _)
test("while2", whileBenchmark2 _)
test("for1", forBenchmark1 _)
test("for2", forBenchmark2 _)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment