测试 RSpec 求实际执行时间

liker · 2015年10月19日 · 最后由 markgeek 回复于 2015年10月20日 · 1905 次阅读

环境:

  • ruby 2.1.2
  • rspec 2.13.0

如题,对自己的创建的 gem,写 spec 测试:需要每一个方法调用的实际执行时间,并保存!

除了对每一个方法添加 benchmark 块之外,有没有其他简单的方法或者可以优化改进的地方?

自己手动实现一下

Rspec.configure do |config|
 config.before(:each) do
   @start_timer = Time.now
 end

  config.after(:each) {}
    puts "Spec ran in #{Time.now - @start_timer}s"
  end
end

#1 楼 @ltl3884 但是这样得到的不是想要的结果("People can method rans in 0.001s")缺少是那个方法消耗的时间

it "do something" do
  method_a
  method_b
end

你是说想要知道method_amethod_b方法的执行时间吗?

RSpec.configure do |config|
  config.example_status_persistence_file_path = "spec.txt"
end

用 RSpec 3.3 跑一遍自己看看文件内容。

#3 楼 @markgeek 恩 是的 并且将结果(每个方法消耗的时间)打印到日志

#5 楼 @liker

一个简单的实现方式:

require 'ruby-prof'

RSpec.configure do |config|
  config.around do |example|
    RubyProf.start
    example.run
    result = RubyProf.stop
    result.eliminate_methods!([/RSpec::.*/])
    printer = RubyProf::FlatPrinter.new(result)
    printer.print(STDOUT)
  end
end

输出:

Measure Mode: wall_time
Thread ID: 4264760
Fiber ID: 25310560
Total: 1.000637
Sort by: self_time

 %self      total      self      wait     child     calls  name
 99.95      1.000     1.000     0.000     0.000        1   Kernel#sleep 
  0.03      1.001     0.000     0.000     1.000        1   Proc#call 
  0.01      0.000     0.000     0.000     0.000        7  *Array#each 
  0.00      1.001     0.000     0.000     1.001        1   Global#[No method] 
  0.00      0.000     0.000     0.000     0.000        2   Kernel#singleton_class 
  0.00      0.000     0.000     0.000     0.000        2   Hash#fetch 
  0.00      0.000     0.000     0.000     0.000        1   Proc#yield 
  0.00      0.000     0.000     0.000     0.000        4  *Class#new 
  0.00      1.000     0.000     0.000     1.000        1   Object#method_a 
  0.00      0.000     0.000     0.000     0.000       12   Symbol#== 
  0.00      0.000     0.000     0.000     0.000        1   Array#reverse_each 
  0.00      0.000     0.000     0.000     0.000        1   Hash#clear 
  0.00      0.000     0.000     0.000     0.000        3   Hash#each_value 
  0.00      1.000     0.000     0.000     1.000        1   BasicObject#instance_exec 
  0.00      0.000     0.000     0.000     0.000        1   Array#reverse 
  0.00      0.000     0.000     0.000     0.000        2   <Module::RSpec>#configuration 
  0.00      0.000     0.000     0.000     0.000        1   Array#pop 
  0.00      0.000     0.000     0.000     0.000        1   Hash#values 
  0.00      0.000     0.000     0.000     0.000        1   Array#last 
  0.00      0.000     0.000     0.000     0.000        1   NilClass#nil? 
  0.00      0.000     0.000     0.000     0.000        2   Mutex#initialize 

* indicates recursively called methods

method_a的执行时间为1s

0.00      1.000     0.000     0.000     1.000        1   Object#method_a

这个还是不好,输出了很多无关的东西,其实已经把 RSpec 的方法调用过滤掉了,否则更多。

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