我有如下基准:
benchmark_result = Benchmark.bm do |x|
x.report { send(test_name) }
end
当我运行它时,我看到两个地方的输出:
send(test_name)
块中的report
。我想继续看到这个输出。我从here看到如何暂时隐藏控制台输出。但问题是我希望内部块继续打印其输出。我只是不想看到基准测试结果。
答案 0 :(得分:3)
当您通过report
或Benchmark::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
虽然看到更好的方法后,这看起来非常黑客。