2016-12-28 38 views
2

我试图比较Rake包含的touch方法,以解决系统触摸问题。在使用Ruby基准测试时防止输出

每个操作输出发送到stdout:

require 'benchmark' 
require 'rake' 

n = 3 
result = Benchmark.bm do |x| 
    x.report("sh:") do 
    n.times { sh "touch foo.txt" } 
    end 
    x.report("touch:") do 
    n.times { touch "bar.txt" } 
    end 
end 

结果:

user  system  total  real 
sh:touch foo.txt 
touch foo.txt 
touch foo.txt 
    0.000000 0.010000 0.030000 ( 0.024775) 
touch:touch bar.txt 
touch bar.txt 
touch bar.txt 
    0.000000 0.000000 0.000000 ( 0.000412) 

我想的是:

user  system  total  real 
sh:touch foo.txt 
    0.000000 0.010000 0.030000 ( 0.024775) 
touch:touch bar.txt 
    0.000000 0.000000 0.000000 ( 0.000412) 

或者别的东西,只有结果。

another question阅读使用Benchmark.measure但下面也不起作用:

require 'benchmark' 
require 'rake' 

n = 3 
result = Benchmark.measure do 
    n.times { sh "touch foo.txt" } 
end 

puts result 

结果:

touch foo.txt 
touch foo.txt 
touch foo.txt 
    0.000000 0.000000 0.010000 ( 0.022931) 

我怎么基准shtouch但防止将标准输出输出?

回答

3

看着the source of sh似乎它接受verbose作为一个选项,以便您正确的调用应该是:

sh "touch foo.txt", verbose: false 

同样can be said of touch

touch "bar.txt", verbose: false 

看来文档不提这些选项。

0

您可以重定向$stdout

见这个例子

puts 1 
original_stdout = $stdout 
$stdout = open("/dev/null", "w") 
puts 2 
$stdout = original_stdout 
puts 3 

它打印

1 
3 

但不打印2

+0

为什么downvote?请评论,以便我可以改进答案。 – akuhn