Easily measuring code execution time in Scala
Recently i was working on big list generation in Scala and was wondering how much time does every approach takes in
same conditions. Let's say that we need to create a list of Ints in range from 1 to 1000 with step == 1. You could do
this in couple ways :
//approach # 1
1 to 1000 by 1 toList
//approach #2
List.range(1,1000, 1)
You could think about other methods as well, but let's keep this 2 simple examples. Now , to calculate time needed to execute this
task you need to introduce small function that will do the job :
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0) + "ns")
result
}
And now in your code instead of :
val list = List.range(1,1000, 1)
You write :
var list = time {List.range(1,1000, 1)} // it will show you : Elapsed time: 104000ns
For first example of list generation we do the same :
var list = time {1 to 1000 by 1 toList} // it will show you : Elapsed time: 93000ns
As you can see, first approach is faster then second . I haven't figured out fully why is it so, but now in my applicationi know what will i use :)
Happy coding