1

我有一个算法,它可能会运行无限时间,并在运行时更新结果。它使用类似于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 中对算法进行时间限制?

更新

性能是一个关键因素。

4

1 回答 1

1

使用超时

best_result = 0
begin
  timeout(5) do
    while true
      new_result = rand
      best_result = new_result if new_result > best_result
    end
  end
rescue Timeout::Error
  puts "That's enough. Result is #{best_result}"
end

这实际上与您正在做的事情相同(在另一个线程中执行,线程在 5 秒后死亡),但从您的代码中抽象了超时处理。它在标准库中。

于 2014-04-22T22:50:42.753 回答