I have an algorithm that can potentially run for an unbounded period of time, updating results as it goes. It's using something similar to an Iterative Deepening Search. After a specified amount of time, I'd like the algorithm to stop so I can use the result it has been calculating.
Here's an example of how I'm accomplishing this using threads:
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
Is there a better way to time-box an algorithm in Ruby?
Update
Performance is a key factor.
Use Timeout.
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
This effectively does the same thing you are doing (execute in another thread, thread gets dead after 5 seconds), but abstracts the timeout handling from your code. And it's in standard library.