System.currentTimeMillis在Scala中无法正常工作

System.currentTimeMillis在Scala中无法正常工作,scala,Scala,我注意到currentTimeMillis方法工作不正确。即使应用程序在30秒内计算出一个阶乘,差异也总是3 object Main extends App { def factorial(n: BigInt) = { val start = currentTimeMillis() @tailrec def rec(acc: BigInt, n: BigInt): BigInt = if (n <= 1) acc else rec(n * acc, n - 1

我注意到
currentTimeMillis
方法工作不正确。即使应用程序在
30
秒内计算出一个阶乘,差异也总是
3

object Main extends App {

  def factorial(n: BigInt) = {
    val start = currentTimeMillis()
    @tailrec
    def rec(acc: BigInt, n: BigInt): BigInt = if (n <= 1) acc else rec(n * acc, n - 1)

    val fac: BigInt = rec(1, n)
    val end = currentTimeMillis()

    ((end - start) / 1000, fac)
  }

  val res = factorial(100000)
  println(s"Get ${res._2} \n in ${res._1} seconds")

}
objectmain扩展应用程序{
def阶乘(n:BigInt)={
val start=currentTimeMillis()
@泰勒克

def rec(acc:BigInt,n:BigInt):BigInt=if(n您的代码没有问题。对于我来说,输出似乎是正确的:

import java.lang.System.currentTimeMillis
import scala.annotation.tailrec

object Main extends App {
  def factorial(n: BigInt) = {
    val start = currentTimeMillis()
    @tailrec
    def rec(acc: BigInt, n: BigInt): BigInt = if (n <= 1) acc else rec(n * acc, n - 1)

    val fac: BigInt = rec(1, n)
    val end = currentTimeMillis()

    ((end - start) / 1000, fac)
  }

  def printTimeForFactorial(n: BigInt) = {
    val res = factorial(n)
    println(s"Factorial of ${n} took ${res._1} seconds")
  }

  printTimeForFactorial(1)
  printTimeForFactorial(1000)
  printTimeForFactorial(10000)
  printTimeForFactorial(50000)
  printTimeForFactorial(100000)
  printTimeForFactorial(110000)
  printTimeForFactorial(120000)
}

你的代码在我看来很不错。你介意分享一下你是如何执行代码的吗?在任何IDE或命令行中的
scalac
,或者…?你计算的30秒可能包括编译时间,运行代码只需要3秒。我使用IntelliJ IDEA Scala插件。
Factorial of 1 took 0 seconds
Factorial of 1000 took 0 seconds
Factorial of 10000 took 0 seconds
Factorial of 50000 took 1 seconds
Factorial of 100000 took 5 seconds
Factorial of 110000 took 6 seconds
Factorial of 120000 took 7 seconds