Ruby 用 Benchmark-ips 量测代码效能

juanito · 2014年06月13日 · 最后由 reboot 回复于 2014年07月18日 · 2844 次阅读

原帖

[benchmark-ips][bips] 是由 Puma 作者 Evan Phoenix(@evanphx)所写的 RubyGem。

安装

$ gem install benchmark-ips

使用方法

首先把库引入,接著用一个 Benchmark.ips do |x| ... end 区块包住要量测的代码,x 实现了一个 report 方法,负责量测代码。

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report("addition") { 1 + 2 }

  x.report("addition2") do |times|
    i = 0
    while i < times
      1 + 2
      i += 1
    end
  end

  x.report("addition3", "1 + 2")
end

report 第一个参数是字串,用来说明量测的是什么。后面放要量测的代码,可以区块、字串形式传入。

原先使用 Ruby 自带的 Benchmark 库,需要预测到底要执行几次,才可以得到信服的结果。

而次数又因各个开发者使用的机器而异。Benchmark-ips 很好的解决了这个问题。

Benchmark-ips 会在 5 秒内尽可能执行代码,告诉你 5 秒内代码可以执行几次(i/s,iteration per second)。

若想更改默认的 5 秒,譬如改成 20 秒:

Benchmark.ips(20) do |x|
  ...
end

上例执行结果:

Calculating -------------------------------------
            addition     72783 i/100ms
           addition2     68922 i/100ms
           addition3     84483 i/100ms
-------------------------------------------------
            addition  5085784.0 (±7.3%) i/s -   25255701 in   4.999724s
           addition2 23843924.9 (±10.0%) i/s -  116960634 in   4.993053s
           addition3 24357200.0 (±7.5%) i/s -  120726207 in   4.997873s

除了排版精美之外,最棒的是会显示标准偏差值,可以更好的了解量测结果。

:)

[bips]: https://github.com/evanphx/benchmark-ips

1 楼 已删除

可以不可以用来对网站进行 benchmark?

可以更好的了解量测结果。棒的。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号