Reputation: 25
I wrote a piece of code which measures code execution time in Scala. I want to write such a code that measures and prints execution time of every step of for loop.
import scala.language.postfixOps
def time[T](block: => T): T = {
val v0 = System.nanoTime()
val res = block
val v1 = System.nanoTime()
println("Execution time: " + (v1 - v0) + "nanoseconds")
res
}
var list = time {1 to 10 by 1 toList} // Execution time: 419830nanoseconds
I get the exact result for this code. But I can't write for every step.
Upvotes: 0
Views: 1266
Reputation: 48420
Try
(1 to 10 by 1).foreach(time(_))
which outputs approximately
Execution time: 8517nanoseconds
Execution time: 603nanoseconds
Execution time: 364nanoseconds
Execution time: 329nanoseconds
Execution time: 339nanoseconds
Execution time: 295nanoseconds
Execution time: 341nanoseconds
Execution time: 312nanoseconds
Execution time: 442nanoseconds
Execution time: 346nanoseconds
Say you had some function applied to each element
def inc(i: Int): Int = i + 1
then you could measure each step like so
(1 to 10 by 1).foreach(v => time(inc(v)))
Upvotes: 2