【发布时间】:2017-06-06 22:33:14
【问题描述】:
最近,我正在学习 Scala 语言。今天我出来一个问题,就是 如何在需要太多时间时终止函数。
例如:
object HelloWorld {
def main(args: Array[String]) {
println("Hello, World")
// How to terminate the sum() function
// when the time that it takes greater than 2 second?
val t0 = System.nanoTime : Double
val total: BigInt = sum(1000000000)
val t1 = System.nanoTime : Double
println("Elapsed time " + (t1 - t0) / 1000000.0 + " msecs")
println(total)
}
//Given that sum() is written by others and I cannot change it.
def sum(k: Int): BigInt = {
var total: BigInt = 0
for (i <- 1 to k) {
total += i
}
total
}
}
上面的scala代码大约需要70s。
【问题讨论】:
标签: scala