Reputation: 19061
I have two ways of finding factorial using Scala. I want to find out how much slower non-tail recursive way is compared to tail-recursive way.
// factorial non-tail recursive
def fact1(n: Int): Int =
if (n==0) 1
else n*fact(n-1)
// factorial tail recursive
def fact(n: Int): Int = {
def loop(acc: Int, n:Int): Int =
if (n==0) acc
else loop(acc*n, n-1)
loop(1, n)
}
// a1 = Time.now
fact1(100)
// a2 = Time.now
// a2-a1
// b1 = Time.now
fact(100)
// b2 = Time.now
// b2-b1
I just wrote up Ruby code for Time.now. Basically, how would you write Time.now
like code in Scala?
Upvotes: 0
Views: 370
Reputation: 32345
You may use the Scala wrapper method scala.compat.Platform.currentTime
which forwards the call to System.currentTimeMillis
.
Upvotes: 0
Reputation: 40461
You can use the java.lang.System
class which provides methods for computing the current time:
currentTimeMillis
for the current time in millisecondsnanoTime
for the current time in nanoseconds (which is recommended now).However, writing good micro-benchmarks is very difficult and it is recommended to rely on a framework for that. Caliper is really good and there is a nice template for projects in scala.
Upvotes: 3