Created
April 6, 2009 15:27
-
-
Save tyru/90799 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
| 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