5

我编写了一个简短的 ruby​​ 脚本来计时我拥有的命令行实用程序的运行时间。我正在使用 ruby​​ 的Benchmark模块:

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

超时使用可能有点粗略,但应该可以满足我的需要。问题Benchmark.bm只是打印基准测试结果。我希望能够将它们保存到一个文件中以供进一步处理(它在一个脚本中运行了几次,所以我不想只消耗终端输出 - 对于这么简单的事情来说似乎太费劲了)

4

1 回答 1

5

这比您想象的要容易,只需将以下行添加到脚本的开头。

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

一切都被重定向到文件,当然如果你需要一些输出到控制台,你将不得不像这样停止重定向。

$stdout = STDOUT

编辑:这里是我用来测试这个的 scipt

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 
于 2013-03-07T15:37:22.087 回答