fork download
  1. require 'benchmark'
  2.  
  3. $__benchmarks__ = []
  4.  
  5. def bench(name, iterations = 1000, &block)
  6. file, line, _ = caller[0].split(':')
  7. $__benchmarks__ << {
  8. file: File.basename(file),
  9. line: line,
  10. name: name,
  11. iterations: iterations,
  12. block: block
  13. }
  14. end
  15.  
  16. at_exit do
  17. Benchmark.bmbm do |x|
  18. $__benchmarks__.each do |info|
  19. benchname = "#{info[:file]}:#{info[:line]} #{info[:name]}"
  20. x.report(benchname) { info[:iterations].times(&info[:block]) }
  21. end
  22. end
  23. end
  24.  
  25. other_array = [*1..1000]
  26.  
  27. bench ".each" do
  28. array = [*1..1000]
  29. other_array.each do |elem|
  30. array << elem
  31. end
  32. end
  33.  
  34. bench "#concat" do
  35. array = [*1..1000]
  36. array.concat(other_array)
  37. end
  38.  
Success #stdin #stdout 0.68s 8048KB
stdin
Standard input is empty
stdout
Rehearsal ------------------------------------------------------
prog.rb:27 .each     0.250000   0.000000   0.250000 (  0.253376)
prog.rb:34 #concat   0.090000   0.000000   0.090000 (  0.086250)
--------------------------------------------- total: 0.340000sec

                         user     system      total        real
prog.rb:27 .each     0.240000   0.010000   0.250000 (  0.251666)
prog.rb:34 #concat   0.090000   0.000000   0.090000 (  0.087623)