我有一个算法,它可能会运行无限时间,并在运行时更新结果。它使用类似于Iterative Deepening Search的东西。在指定的时间后,我希望算法停止,这样我就可以使用它一直在计算的结果。
这是我如何使用线程完成此操作的示例:
best_result = 0
thread = Thread.new {
while true
new_result = rand
best_result = new_result if new_result > best_result
end
}
sleep 5
thread.exit
puts best_result
有没有更好的方法在 Ruby 中对算法进行时间限制?
更新
性能是一个关键因素。