运行 基准测试但不打印结果

Run benchmark but don't print the result

我有如下基准:

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

当我 运行 这样做时,我看到来自两个地方的输出:

  1. report 块中的 send(test_name)。我想继续看到这个输出。
  2. 基准块的输出,即生成的基准报告被打印到控制台。我不希望发生这种情况。

我从 here 了解到如何暂时隐藏控制台输出。但问题是我希望内部块继续打印其输出。我只是不想看到基准测试结果。

当您在 Benchmark.bmBenchmark.benchmark 发送到块的 Benchmark::Report 对象上调用 report 方法时,它将打印到 STDOUT。如果您只对基准指标感兴趣而不打印报告,您可以这样做:

benchmark_result = Benchmark.measure do
  send(test_name) 
end

它 returns 一个 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>

如果您只对用于执行您的块的实际运行时间感兴趣,请执行以下操作 (returns a Float):

benchmark_result = Benchmark.realtime do
  send(test_name) 
end

我接受了 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

虽然在看到更好的方法后,这看起来很老套。