最近,我正在学习Scala语言。今天我提出一个问题,那就是, 如何在需要太多时间终止一个函数。如何在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
}
}
上面阶代码需要大约70。
你能不能给我一个小的演示,因为我不不知道'Thread'。谢谢。我在工作中使用Maple和MATLAB大约5年。 – xyz
您可以参考https://twitter.github.io/scala_school/concurrency.html#Thread。有关线程的简短介绍。 – markusthoemmes
@markusthoemmes为什么不是'未来'的方式去这里?如果在“未来”区块中计算时间,则“未来”管理应该不会对时间测量产生任何影响(至少,这是我的理解)。 –