fork download
  1. import scala.annotation.tailrec
  2.  
  3. object Main extends App {
  4.  
  5. val n = 1000000
  6.  
  7. val a = System.nanoTime()
  8. var sum1 = 0L
  9. for(i <- 1 to n) sum1 += i
  10. val b = System.nanoTime()
  11.  
  12. println(s"$sum1 , for loop time: ${b - a}")
  13.  
  14. val c = System.nanoTime()
  15. var sum2 = 0L
  16. var i = 1
  17. while(i <= n) {
  18. sum2 += i
  19. i += 1
  20. }
  21. val d = System.nanoTime()
  22.  
  23. println(s"$sum1 , while loop time: ${d - c}")
  24.  
  25. val e = System.nanoTime()
  26. @tailrec def rec(sum: Long, i: Int) : Long =
  27. if(i > n) sum else rec(sum + i, i + 1)
  28.  
  29. val sum3 = rec(0L, 1)
  30.  
  31. val f = System.nanoTime()
  32. println(s"$sum3 , tailrec time: ${f - e}")
  33.  
  34. }
Success #stdin #stdout 0.39s 322432KB
stdin
Standard input is empty
stdout
500000500000 , for loop time: 127097588
500000500000 , while loop time: 3253564
500000500000 , tailrec time: 1812719