In Ruby, how do I properly read the results of benchmark?

Viewed 1260

I'm using Rails 5.0.1. With the rails console, I would like to figure out what is the fastest way to get the index of the first regular expression occurrence in a string. So I have tried the below

2.4.0 :004 > Benchmark.bm do |x|
2.4.0 :005 >     x.report { 50000.times { a = 'a@b.c'.index(/\@/) } }
2.4.0 :006?>     x.report { 50000.times { a = 'a@b.c'.match(/\@/)[0] } }
2.4.0 :007?>   end
       user     system      total        real
   0.030000   0.000000   0.030000 (  0.026763)
   0.060000   0.000000   0.060000 (  0.064986)
 => [#<Benchmark::Tms:0x007fe974e13f88 @label="", @real=0.026763000059872866, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.03000000000000025, @total=0.03000000000000025>, #<Benchmark::Tms:0x007fe973c9e9d8 @label="", @real=0.06498600030317903, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.06000000000000005, @total=0.06000000000000005>]

I'm confused about how to read the results. I "think" its telling me the first method takes an average of ".02" seconds while the second requires ".06" seconds, so I should stick with "index". Am I reading this right?

2 Answers

"real" is the most simple and (probably) relevant thing to look at. It's simply the amount of time that has passed on the clock. t = Time.now; do_things; real=Time.now-t.

You can ignore the other columns.

you said "an average of" - it's not an average, it's the amount of time that it takes to do your code 50,000 times. So the average time to do it once is real/50_000. (but you don't need to calculate this to know that index is faster).

Related