最近,我正在學習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爲什麼不是'未來'的方式去這裏?如果在「未來」區塊中計算時間,則「未來」管理應該不會對時間測量產生任何影響(至少,這是我的理解)。 –