运行基准但不打印结果

时间:2016-05-01 16:58:55

标签: ruby benchmarking

我有如下基准:

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

当我运行它时,我看到两个地方的输出:

  1. send(test_name)块中的report。我想继续看到这个输出。
  2. Benchmark块的输出,即生成的基准报告将打印到控制台。我不希望这种情况发生。
  3. 我从here看到如何暂时隐藏控制台输出。但问题是我希望内部块继续打印其输出。我只是不想看到基准测试结果。

2 个答案:

答案 0 :(得分:3)

当您通过reportBenchmark::Report调用发送到块的Benchmark.bm对象上的Benchmark.benchmark方法时,它将打印到STDOUT。如果您只是对基准指标感兴趣而不打印报告,则可以执行以下操作:

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

答案 1 :(得分:0)

我接受了阿米特的答案,因为它似乎是规范的,但我确实找到了另一种方法来同时做到这一点。

this question我添加了以下代码(稍加修改以在touch/rm文件中包含null.txt次调用):

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

虽然看到更好的方法后,这看起来非常黑客。