require 'timeout'
def do_something
Timeout::timeout(9) do
sleep 10
end
rescue Timeout::Error => e
puts "Something near line #{__LINE__} is taking too long!"
# or, count backwards in method
puts "Line #{__LINE__ - 5} is taking too long!"
end
do_something
如果超时块超时并引发超时错误,这将停止执行。如果您想继续执行,您可能会使用基准测试做得更好:
require 'benchmark'
time = Benchmark.realtime do
sleep 10
end
puts "Line #{__LINE__ - 2} is slow" if time > 9
一个基准块可以有多个计时器:
Benchmark.bm do |b|
b.report('sleeping:') { sleep 3 }
b.report('chomping:') { " I eat whitespace ".chomp }
end
在此处查看有关基准的更多信息:
http ://ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html
如果您想跟踪正在执行的行号,为什么不尝试将其传递给自定义方法,如下所示:
def timethis(line, &block)
if Benchmark.realtime(&block) > 2
puts "Line #{line} is slow"
end
end
timethis(__LINE__) { sleep 1 }