Created
July 24, 2012 15:00
-
-
Save Sciss/3170507 to your computer and use it in GitHub Desktop.
Bench2.scala
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
package benchmark | |
object Bench2 extends App { | |
val num = args.headOption.map(_.toInt).getOrElse(1000) | |
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 | |
//println( "num = " + num ) | |
while(i < times) { | |
while(j < num) { | |
while(k < num) { | |
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 < num) { | |
while(k < num) { | |
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 num; k <- 0 until num) | |
obj = new Object | |
} | |
} | |
def forBenchmark2(times: Int) = { | |
time{ | |
var x: Long = 0 | |
for(i <- 0 until times; j <- 0 until num; k <- 0 until num) | |
x += 1 | |
} | |
} | |
def test(name: String, bench: Int => Long) { | |
println(name + " took " + bench(10000)/10000000.0 + " µs per run" ) | |
} | |
println( "Running benchmarks for n = " + num ) | |
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