Raw Syntax

The stuff programs are made of

Measuring Slow Code

Permalink

Over the years I've found myself needing a quick way to measure some slow code. Whether I'm looking at a 100 line function or a 10 line controller action, sometimes I just need some quick print statements to determine which part of the code is slow.

My original approach to doing this would be to mark off sections of the code with Time.now statements printing out how many seconds each section took. This approach is messy because it requires altering the code a good deal. And at the end I was left comparing sections of the code to figure out which part was slower than all the other parts -- doing the math in my head.

Use Benchmark?

Ruby has a Benchmark class built in. I tried using it. While it can be helpful in certain situations, if I'm measuring 5 sections of a function there's an awful lot of code rewriting that has to happen because of the Benchmark blocks messing with the scope of variables. That was more work than it was worth.

Roll my Own

I'm hesitant to reinvent the wheel, but in this case I created a very simple gem to address my needs. It's called CodeTimer. To use it first you instantiate it:

ct = CodeTimer.new

Then you insert markers for each part that you want to measure:

ct.start("Part1")
# ... slow code here ...
ct.start("Part2")
# ...

And a marker for stopping measuring:

ct.end

It returns a formatted string:

Total Time: 17s
Part1:   11% / 2s
Part2:   29% / 5s
Part3:   47% / 8s
Part4:   11% / 2s

And it's easy to see that Part3 is the slowest section. Better start trying to speed up the code there.

What If This Doesn't Work?

This isn't the solution for every slow code problem. If this approach doesn't yield meaningful results you will have to use a more serious tool. However, I reach for this tool first because it's the simplest thing that could possibly work.

Comments