使用Ruby基准测试时防止输出
我试图将Rake包含的方法与系统触摸进行比较 每个操作都将输出发送到标准输出:使用Ruby基准测试时防止输出,ruby,Ruby,我试图将Rake包含的方法与系统触摸进行比较 每个操作都将输出发送到标准输出: 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
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)
touch foo.txt
touch foo.txt
touch foo.txt
0.000000 0.000000 0.010000 ( 0.022931)
我想要的是:
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)
或者其他只有结果的东西
我读到这篇文章是为了使用基准。度量,但以下内容也不起作用:
require 'benchmark'
require 'rake'
n = 3
result = Benchmark.measure do
n.times { sh "touch foo.txt" }
end
puts result
结果:
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)
touch foo.txt
touch foo.txt
touch foo.txt
0.000000 0.000000 0.010000 ( 0.022931)
如何对sh
和touch
进行基准测试,但防止输出进入标准输出?查看它似乎接受verbose
作为选项,因此正确的调用应该是:
sh "touch foo.txt", verbose: false
同样:
文件中似乎根本没有提到这些选项 您可以重定向$stdout
看这个例子
puts 1
original_stdout = $stdout
$stdout = open("/dev/null", "w")
puts 2
$stdout = original_stdout
puts 3
哪张照片
1
3
但是不打印2
为什么要投否决票?请评论,以便我可以改进答案。