2012-09-08 42 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