Reputation: 418
I benchmarked the execution time for method
tests.each do |test|
time = Benchmark.realtime { method(test) }
end
def method(test)
code
end
Which is returning time in seconds
But what I want is to break the loop if this method is taking more than 30 sec of execution time.
suggest a clean way to do it.
Upvotes: 0
Views: 763
Reputation: 8345
You already got several answers, especially some regarding Timeout
.
Please be cautious here. Timeout
is implemented with an ALARM signal in standard ruby (i.e., I'm not talking about JRuby here), which means
If you can, it will always be safer to somehow do your timeout yourself. That is, if you can, then have your method
check for time spent regularly. Of course, this may or may not be useful to you; you don't want to bring test stuff into your production code. And it may be hard if you want to timeout system calls (for example, blocking network calls).
At least, keep it in mind.
Upvotes: 1
Reputation: 18444
Use stdlib Timeout
require 'timeout'
def method(test)
Timeout::timeout(30){
#code here
}
end
This will raise Timeout::TimeoutError
if code takes longer to run
Upvotes: 3
Reputation: 4920
Try this:
tests.each do |test|
time = Benchmark.realtime { method(test) }
break if time > 30
end
Not sure about the unit of time
. Adjust the condition time > 30
according to that.
Upvotes: -2
Reputation: 1357
You can use Ruby Timeout method
require 'timeout'
tests.each do |test|
Timeout::timeout(30) {
method(test)
}
end
Upvotes: 1