【问题标题】:Run benchmark but don't print the result运行基准测试但不打印结果
【发布时间】:2023-04-10 23:04:01
【问题描述】:

我有一个如下基准:

benchmark_result = Benchmark.bm do |x|
  x.report { send(test_name) }
end

当我运行它时,我看到了来自两个地方的输出:

  1. report 块中的send(test_name)。我想继续看到这个输出。
  2. 基准块的输出,即生成的基准报告打印到控制台。我不希望这种情况发生。

我从here 看到了如何临时隐藏控制台输出。但问题是我希望内部块继续打印其输出。我只是不想看到基准测试结果。

【问题讨论】:

  • 您想查看方法调用的输出但显示基准输出?我不知道你为什么要对某些东西进行基准测试然后扔掉结果。
  • 我正在制作一个“基准缓存”系统,这样当我请求一个方法的基准时,我不必再次实际运行该方法。这专门针对长时间运行的方法,我承认结果不会完全准确。人们在我最近发布的问题here 中多次告诉我这一点。基本上,每当我运行测试用例时,我都会存储基准,稍后会显示。
  • 一个有趣的项目,感谢您的解释。我认为 AmitA 的方法是最好的,您可以捕获结果并以某种方式保存它们以供以后使用。实际上,您可以将它们放在一些小型数据库中,例如 SQLite,以便在必要时更好地组织它们。

标签: ruby benchmarking


【解决方案1】:

当你在Benchmark.bmBenchmark.benchmark 发送到块的Benchmark::Report 对象上调用report 方法时,它将打印到STDOUT。如果您只对基准指标感兴趣而不打印报告,您可以这样做:

benchmark_result = Benchmark.measure do
  send(test_name) 
end

它返回一个如下所示的Benchmark::Tms 对象:

 => #<Benchmark::Tms:0x007fb5b1b40118
 @cstime=0.0,
 @cutime=0.0,
 @label="",
 @real=4.5693013817071915e-05,
 @stime=0.0,
 @total=0.0,
 @utime=0.0>

如果您只对执行块所用的实时时间感兴趣,请执行以下操作(返回 Float):

benchmark_result = Benchmark.realtime do
  send(test_name) 
end

【讨论】:

  • 我多次使用Benchmark,但从未真正阅读过doc。不错的主意。
【解决方案2】:

我接受了 Amit 的回答,因为它看起来很规范,但与此同时我确实想出了另一种方法。

来自this question 我添加了以下代码(稍作修改以包含touch/rmnull.txt 文件的调用):

def silence_output
  # Store the original stderr and stdout in order to restore them later
  @original_stderr = $stderr
  @original_stdout = $stdout

  # Redirect stderr and stdout
  `touch null.txt`
  $stderr = File.new(File.join(File.dirname(__FILE__), 'null.txt'), 'w')
  $stdout = File.new(File.join(File.dirname(__FILE__), 'null.txt'), 'w')
end

# Replace stderr and stdout so anything else is output correctly
def enable_output
  $stderr = @original_stderr
  $stdout = @original_stdout
  @original_stderr = nil
  @original_stdout = nil
  `rm null.txt`
end

有了这个,我可以使用以下方法实现我的目标:

silence_output
benchmark_result = Benchmark.bm do |x|
  x.report do   
    enable_output
    send(test_name)
    silence_output
  end
end
enable_output

虽然在看到更好的方法后,这似乎很hacky。

【讨论】:

    猜你喜欢
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2013-11-19
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多