首页 > 解决方案 > 准确计时 RSpec 规范

问题描述

我有 2 个测试。一个使用数据库调用,一个使用双精度。我想了解它们之间的性能差异。我意识到这可能非常小,但我只是想在选择使用存根或实际调用数据库时更好地了解权衡的延迟方面。

我最初认为这就像运行类似的东西一样简单

time rspec spec_with_db_spec.rb

time rspec spec_with_double_spec.rb

独立地并且可能以随机顺序一遍又一遍地重复,所以我可以取平均值,但是,我遇到了一些问题。

  1. 这似乎time不是最好的方法,因为它可能恰好与我的计算机上同时发生的一个特别昂贵的过程相吻合。我想一遍又一遍地运行它可以帮助解决这个问题,但我不确定。
  2. 我意识到我也许可以使用 RSpec 的时间输出,但是基于(尽管是旧的)帖子,这似乎不可靠。

有人对此有想法吗?它不需要是完美的,而只是我可以运行并看到差异以及差异大约有多少(数量级很好)。

标签: ruby-on-railsperformancetimerspec

解决方案


您可以使用 Rubys 内置Benchmark 工具

require 'rails_helper'
require 'benchmark' # from the stdlib

RSpec.describe 'Benchmark' do
  let(:create_bm) do
    Benchmark.bm { FactoryBot.create_list(:user, 100) } 
  end

  let(:build_bm) do
    Benchmark.bm { FactoryBot.build_list(:user, 100) } 
  end

  it 'can give you the total time' do
    pending "Creating the list took #{create_bm.total} seconds"
  end

  specify 'you do not need two separate spec files' do
    pending "Building the list took #{build_bm.total} seconds"
  end

  specify 'stubbing is faster' do
    expect(build_bm.total).to be < create_bm.total
  end
end

推荐阅读