2016-05-01 56 views
0

我有一個基準像如下:從兩個地方運行基準,但不打印結果

benchmark_result = Benchmark.bm do |x| 
    x.report { send(test_name) } 
end 

當我運行它,我看到輸出:

  1. send(test_name)report區塊。我想繼續看到這個輸出。
  2. 基準測試塊的輸出,即生成的基準測試報告將打印到控制檯。我不希望發生這種情況。

我從here看過如何暫時隱藏控制檯輸出。但問題是我想要內部塊繼續打印它的輸出。我只是不想看到基準測試結果。

+2

您希望看到方法調用的輸出,但不*顯示基準輸出?我不知道你爲什麼要做一些基準測試,然後拋出結果。 – tadman

+0

我正在制定一個'基準緩存'系統,以便當我爲某個方法請求基準時,我不必再實際運行該方法。這是專門用於長時間運行的方法,我認識到結果不會完全準確。人們在我最近發佈的問題[這裏]告訴我這麼多次(http://stackoverflow.com/questions/36961017/how-to-multiply-a-benchmark?noredirect=1#comment61480374_36961017)。基本上,每當我運行測試用例時,我都會存儲基準,並在稍後顯示。 –

+0

一個有趣的項目,謝謝解釋。我認爲AmitA的方法可以捕獲結果並以某種方式將它們保存以備後用。實際上,您可以將它們放在一些小數據庫中,如SQLite,以便在需要時進行更好的組織。 – tadman

回答

3

當您通過Benchmark.bmBenchmark.benchmark調用Benchmark::Report對象上的report方法時,它將打印到標準輸出。如果你是在基準指標不打印報告有興趣,你可以這樣做:

benchmark_result = Benchmark.measure do 
    send(test_name) 
end 

它返回一個Benchmark::Tms對象,看起來像這樣:

=> #<Benchmark::Tms:0x007fb5b1b40118 
@cstime=0.0, 
@cutime=0.0, 
@label="", 
@real=4.5693013817071915e-05, 
@stime=0.0, 
@total=0.0, 
@utime=0.0> 

如果你只是有興趣在用來執行你的塊經過實時,請執行下列操作(返回Float):

benchmark_result = Benchmark.realtime do 
    send(test_name) 
end 
+0

我多次使用'Benchmark',但從未真正閱讀[doc](http://ruby-doc.org/stdlib-2.3.0/libdoc/benchmark/rdoc/Benchmark.html)。不是一個壞主意。 –

0

我已經接受Amit的答案,因爲它似乎是規範的,但我確實找到了另一種方式來做到這一點。

this question我加入以下代碼(略作修改,包括對null.txt文件touch/rm話費):

def silence_output 
    # Store the original stderr and stdout in order to restore them later 
    @original_stderr = $stderr 
    @original_stdout = $stdout 

    # Redirect stderr and stdout 
    `touch null.txt` 
    $stderr = File.new(File.join(File.dirname(__FILE__), 'null.txt'), 'w') 
    $stdout = File.new(File.join(File.dirname(__FILE__), 'null.txt'), 'w') 
end 

# Replace stderr and stdout so anything else is output correctly 
def enable_output 
    $stderr = @original_stderr 
    $stdout = @original_stdout 
    @original_stderr = nil 
    @original_stdout = nil 
    `rm null.txt` 
end 

有了這個,我可以通過完成我的目標如下:

silence_output 
benchmark_result = Benchmark.bm do |x| 
    x.report do 
    enable_output 
    send(test_name) 
    silence_output 
    end 
end 
enable_output 

雖然看到更好的方式來做到這一點,但這看起來很詭異。