2

I'm trying to compare the touch method that Rake includes to shelling out to the system touch.

Each operation is sending output to 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

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)

What I'd like is:

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)

Or something else that only has the results.

I read in another question to use Benchmark.measure but the following also doesn't work:

require 'benchmark'
require 'rake'

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

puts result

result:

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

How do I benchmark sh and touch but prevent output from going to stdout?

Community
  • 1
  • 1
mbigras
  • 7,664
  • 11
  • 50
  • 111

2 Answers2

3

Looking at the source of sh it seems it accepts verbose as an option so the right invocation for you should be:

sh "touch foo.txt", verbose: false

The same can be said of touch:

touch "bar.txt", verbose: false

It seems the docs don't mention these options at all.

Greg Navis
  • 2,818
  • 10
  • 10
0

You can redirect $stdout

See this example

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

Which prints

1
3

But does not print 2

akuhn
  • 27,477
  • 2
  • 76
  • 91