Skip to content

Instantly share code, notes, and snippets.

@tyru
Created April 6, 2009 15:27
Show Gist options
  • Select an option

  • Save tyru/90799 to your computer and use it in GitHub Desktop.

Select an option

Save tyru/90799 to your computer and use it in GitHub Desktop.
import scala.testing.Benchmark
import java.util.Timer
class For(MAX_LOOP:Int) {
var sum:Int = 0
def run() = {
println("iterate " + MAX_LOOP + " times...")
val start:Long = System.currentTimeMillis()
for (val n <- 1 to MAX_LOOP) sum += n
val end:Long = System.currentTimeMillis()
println("For: " + (end - start) + " ms")
}
println(MAX_LOOP + " times of loop of For")
assert(MAX_LOOP > 0)
}
class ForEach(MAX_LOOP:Int) {
var sum:Int = 0
def run() = {
println("iterate " + MAX_LOOP + " times...")
val start:Long = System.currentTimeMillis()
(1 to MAX_LOOP).foreach((n) => sum += n)
val end:Long = System.currentTimeMillis()
println("ForEach: " + (end - start) + " ms")
}
println(MAX_LOOP + " times of loop of ForEach")
assert(MAX_LOOP > 0)
}
class ForPrimitive(MAX_LOOP:Int) {
var sum:Int = 0
def run() = {
println("iterate " + MAX_LOOP + " times...")
val start:Long = System.currentTimeMillis()
var i:Int = 1
while (i <= MAX_LOOP) {
sum += i
i += 1
}
val end:Long = System.currentTimeMillis()
println("ForPrimitive: " + (end - start) + " ms")
}
println(MAX_LOOP + " times of loop of ForPrimitive")
assert(MAX_LOOP > 0)
}
object Main extends Application {
val MAX_LOOP = 100 * 1000 * 1000
val eachTest:Array[Benchmark] = Array[Benchmark](
new For(MAX_LOOP) with Benchmark,
new ForEach(MAX_LOOP) with Benchmark,
new ForPrimitive(MAX_LOOP) with Benchmark
)
for (val bench:Benchmark <- eachTest)
bench.run
println
}
// vim:ft=scala:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment