Vishwas Nahar
Vishwas Nahar

Reputation: 418

break if method takes more than 30sec time to execute

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

Answers (4)

AnoE
AnoE

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

  • You cannot nest timeouts (that is, you can, but it will silently fail).
  • If your code or some gem also uses the ALARM signal, it will go wrong.
  • Things can go plainly wrong (unexpected behaviour) due to it being such a clunky mechanism.
  • Don't even try to mix it with the "green multithreading" of standard ruby unless you like to have major headaches.

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

Vasfed
Vasfed

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

Jagdeep Singh
Jagdeep Singh

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

Maxim Fedotov
Maxim Fedotov

Reputation: 1357

You can use Ruby Timeout method

require 'timeout'

tests.each do |test|
  Timeout::timeout(30) {
    method(test)
  }
end

Upvotes: 1

Related Questions