Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving ruby's benchmark output to a file

I wrote a short ruby script to time the run of a command line utility I have. I'm using the ruby's Benchmarkmodule as so:

Benchmark.bm(" "*7 + CAPTION, 7, FMTSTR, ">avg:") do |bench|
  #this loops over a  couple of runs
  bench.report("Run #{run}: ") do
    begin
    Timeout::timeout(time) {
      res = `#{command}`
    }
    rescue Timeout::Error
    end
  end
end

The timeout use is probably a bit crude but should be ok for my needs. The problem is Benchmark.bm just prints the benchmark results. I'd like to be able to save them to a file for further processing (it's run a couple of times in a single script so I don't want to just consume the terminal output - seems way too much effort for something this simple)

like image 224
mck Avatar asked Mar 07 '13 14:03

mck


1 Answers

That is easier than you might think, just add the following lines to the beginning of your script.

$stdout = File.new('benchmark.log', 'w')
$stdout.sync = true

And everything is redirected to the file, off course if you need some output to the console you will have to stop the redirection like this.

$stdout = STDOUT

EDIT: here the scipt i used to test this

require 'benchmark' 

$stdout = File.new('console.out', 'w')
$stdout.sync = true

array = (1..100000).to_a 
hash = Hash[*array]

Benchmark.bm(15) do |x| 
  x.report("Array.include?") { 1000.times { array.include?(50000) } } 
  x.report("Hash.include?")  { 1000.times { hash.include?(50000) } } 
end 
like image 199
peter Avatar answered Sep 20 '22 18:09

peter