The built-in profiler, and even ruby-prof, add a lot of overhead to the interpreter. This reduces their usefulness. If I don’t know why my program is slow, I use ruby-prof. However…

benchmark, i choose you!

Sometimes I already know the source of the problem, and just need to see if my changes are making a difference or not. So I added a little guy to my .irbrc file:

def benchmark
  cur =
  result = yield
  print "#{cur = - cur} seconds"
  puts " (#{(cur / $last_benchmark * 100).to_i - 100}% change)" rescue puts ""
  $last_benchmark = cur

Now I can benchmark {} any block and get the wall clock running time, as well as the percent change (+ or -) from the last run. As they say on the street: schwing!

4 responses

  1. Nice function.

    This works a lot better than Ruby’s in-built Benchmark, which I couldn’t get it to work.

    I did my test in script/console, and got a lot of values returned to me. i.e. after =>. I might be a good idea to return 0.

  2. Not sure what you mean…are you saying you don’t want to see the value of the block you ran?

    Anyway it’s easy enough for each reader to implement their own personal version.