Ruby performance tuning with ruby-prof

Joeri Poesen //

I've been working on a multithreaded ruby server/process monitor to keep track of a number of production environments. I'll be writing up on the specifics later on, including the related python/ruby showdown with Bert Heymans.

Today however, I'm going to focus on a specific problem I encountered: the ruby process immediately took up somewhere between 95% and 99% of the CPU. Not good.

Enter ruby-prof, a mean and fast ruby code profiler helps you figure out exactly which bits of code are hogging the resources. It even produces text files and nicely formatted html graphs. Ooh, shiny! Indeed.

Simply install ruby-prof as a gem and run

ruby-prof --printer=graph_html --file=myoutput.html myscript.rb

In my case, this exposed the fact that was being called approximately 2 million times in 30 seconds, and that - unsurprisingly - most of the time was spent instantiating Time objects.

I no longer blame my cpu for going nuts.

I was trying to introduce timed event handling to make sure my scheduled monitoring processes run every x seconds. I solved this by entering an endless loop (while (true)) and on each iteration comparing the difference between and the end time of the moment the action finished last. Bad idea.

I replaced this brainfart with a

sleep (my_interval)

that's called after the monitoring action has been executed. Problem solved and my script doesn't even show up in the top list anymore.


* ruby-prof project page

* Charlie Savage on ruby-prof.0.4.0

* O'Reilly ruby: Profiling Ruby code with ruby-prof