ruby-on-rails - 准确计时 RSpec 规范
问题描述
我有 2 个测试。一个使用数据库调用,一个使用双精度。我想了解它们之间的性能差异。我意识到这可能非常小,但我只是想在选择使用存根或实际调用数据库时更好地了解权衡的延迟方面。
我最初认为这就像运行类似的东西一样简单
time rspec spec_with_db_spec.rb
和
time rspec spec_with_double_spec.rb
独立地并且可能以随机顺序一遍又一遍地重复,所以我可以取平均值,但是,我遇到了一些问题。
- 这似乎
time
不是最好的方法,因为它可能恰好与我的计算机上同时发生的一个特别昂贵的过程相吻合。我想一遍又一遍地运行它可以帮助解决这个问题,但我不确定。 - 我意识到我也许可以使用 RSpec 的时间输出,但是基于(尽管是旧的)帖子,这似乎不可靠。
有人对此有想法吗?它不需要是完美的,而只是我可以运行并看到差异以及差异大约有多少(数量级很好)。
解决方案
您可以使用 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
推荐阅读
- html - 在引导程序 4 中将左侧垂直导航与顶部导航重叠
- json - 无法在 Spring MVC 控制器中对 POST 请求发送 json 响应
- ios - 核心蓝牙:确定设备是否可用于重新连接
- python - 无法更改 Anaconda .condarc 文件的配置
- scala - Scala 错误:java.sql.SQLException:找不到适合 jdbc:calcite 的驱动程序:
- imagemagick - Imagemagick - 在平铺蒙太奇内移动/偏移图像?
- r - 使用 R 中多个“键”列中的值将数据帧从长格式复杂地重塑为宽格式
- php - 选择框显示 db 值不允许更新
- amazon-web-services - AWS step 函数可以执行超过 25000 次吗?
- c# - 获取第一个表插入值到第二个表