Recently, I am learning the Scala language. Today I come out a question, that is, how to terminate a function when it takes too many time.
For example:
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
}
}
The above scala code takes about 70s.