在 RUBY 中 运行 断言语句的平均时间?

Average time to run an assert statement in RUBY?

我知道这是一个有点开放性的问题,但我刚刚接管了 运行ning 一个使用 RUBY 的自动化包,需要对其进行性能改进。

我想知道是否有人知道在 Ruby 中 运行 一个简单的断言(真、假、相等等)需要多长时间?

有些测试很长 运行ning 并且包含很多断言(一个测试超过 7000!)。

能够消除即使只是几个经常调用的断言也会有很大帮助。在我们花时间重构之前,我只需要能够在纸面上向我的经理证明好处。

新手感谢您提供的任何帮助!! 谢谢, 簇绒

断言本身非常快。在下面的规范中,您可以看到可以在不到一秒的时间内轻松做出 14,000 个断言。

require 'rspec/autorun'

RSpec.describe 'assert' do
  it 'is fast for a simple comparision' do
    7000.times { expect(1).to eq(1) }
  end

  it 'is fast for include' do
    7000.times { expect("aasdfas flsajfalds jfdsf lksa jfd test asfdsadf sadfsadf").to include('test') }
  end
end
#=> Finished in 0.0312 seconds (files took 0.1092 seconds to load)
#=> 2 examples, 0 failures

浏览器的检查使断言变慢。在下面的规范中,您可以看到仅检查文本 100 次就需要 50 秒。

require 'rspec/autorun'
require 'watir-webdriver'

RSpec.describe 'assert url' do
  it 'is fast for include' do
    start_setup = Time.now
    browser = Watir::Browser.new :chrome
    browser.goto('http://www.example.com/')
    puts "start browser: #{Time.now - start_setup} seconds"

    100.times { expect(browser.text).to include('illustrative') }
  end
end
#=> start browser: 1.947 seconds
#=> Finished in 52.92 seconds (files took 0.441 seconds to load)
#=> 1 example, 0 failures

删除对浏览器的重复调用,使我们能够再次快速做出许多断言(除了浏览器设置)。

require 'rspec/autorun'
require 'watir-webdriver'

RSpec.describe 'assert url' do
  it 'is fast for include' do
    start_setup = Time.now
    browser = Watir::Browser.new :chrome
    browser.goto('http://www.example.com/')
    puts "start browser: #{Time.now - start_setup} seconds"

    text = browser.text
    7000.times { expect(text).to include('illustrative') }
    7000.times { expect(text).not_to include('some other text') }
  end
end
#=> start browser: 1.972 seconds
#=> Finished in 2.75 seconds (files took 0.3432 seconds to load)
#=> 1 example, 0 failures

总而言之,断言很快,但检查浏览器很慢。如果删除断言减少了对浏览器的调用次数,则只会加快测试套件的速度。