2012-09-08 111 views
1

如何在Ruby中创建一个采用任意函数调用的简单定时器方法?如何在Ruby中创建简单的计时器方法?

例如: time rspectime get_primes(54784637)

应该仍然返回在(get_primes)通过函数的结果。

下不做得比较工作:

def time block 
    t = Time.now 
    result = eval(block) 
    puts "\nCompleted in #{(Time.now - t).format} seconds" 
    result 
end 

的Ruby 1.9.3

+0

你实现这种功能已经存在的标准['benchmark'](http://ruby-doc.org/stdlib-1.9.3 /libdoc/benchmark/rdoc/Benchmark.html)库? – Gareth

回答

5

它更Rubyesque使用块:

def time 
    t = Time.now 
    result = yield 
    puts "\nCompleted in #{Time.now - t} seconds" 
    result 
end 

time { rspec } 
+0

我现在明白收益率是多少。 (最后。) –

+0

太棒了。谢谢! –

2

试试这样说:

def time(&block) 
    t = Time.now 
    result = block.call 
    puts "\nCompleted in #{(Time.now - t)} seconds" 
    result 
end 
+0

你的意思是'block.call'? – Gareth

2

此功能是al准备在Ruby的标准库可用,Benchmark模块:

require 'benchmark' 

time = Benchmark.realtime { 10_000.times { print "a" } } 
+0

除了它不返回块的结果,这是OP想要的结果。 –

+0

对不起,我不是在为他做OP的工作,只是告诉他他的问题的时间计算部分已经为他解决了。 – Gareth