This post originated from an RSS feed registered with Ruby Buzz
by Ryan Davis.
Original Post: Ruby Go Zoom Zoom
Feed Title: Polishing Ruby
Feed URL: http://blog.zenspider.com/index.rdf
Feed Description: Musings on Ruby and the Ruby Community...
Everyone knows that ruby isn't fast. (no, it isn't deja-vu--read on) Its true, Ruby isn't fast. Matz himself gave a keynote at the Seattle RubyConf titled something like "Ruby: Fast, but Good" (please send me corrections if I misremember).
So, yeah. Slow. "Cool," I say, "most of the time it is fast enough". When it isn't fast enough what you (should) do is:
Exhaust all pure-ruby options:
Think about your design and make sure it is correct/optimal.
Look into trading off memory for speed (ie, caching like mad).
Double check to see if someone else has already solved your problem, etc etc.
Profile your code
Identify and possibly refactor bottlenecks into bite sized chunks.
Rewrite the bottlenecks in C.
If you are lazy (smart?? nah...) like me, you'll use RubyInline to cut your C development time to a minimum... Most of the time, this isn't too hard, and if you use RubyInline, then you don't really spend any extra time dealing with makefiles/extconfs/setups/etc.
Imagine
% time ruby factorial.rb 5000000
Iter = 5000000, T = 67.23166600 sec, 0.00001345 sec / iter
real 1m7.310s
user 0m55.980s
sys 0m0.280s
That is not a terribly long time to be running, but factorial??? c'mon. It shouldn't be that slow for just 5 million calls! If we ran a profiler on the code, we'd see that in fact, the method factorial is where nearly all time is being spent. We could pop in a quick call to inline and convert it to C and ZOOOOM!
But... what if you didn't have to write C code???
What if... all you had to do was add -rzenoptimize to the command-line??
% time ruby -rzenoptimize factorial.rb 5000000
*** Optimizer threshold tripped!! Optimizing Factorial.factorial
Iter = 5000000, T = 13.30087900 sec, 0.00000266 sec / iter
real 0m14.382s
user 0m12.550s
sys 0m0.290s
And ZOOM! is automatic reducing your runtime from 67 seconds to 14 seconds, almost a 5x increase in speed. Wouldn't that be nice? What if you could do that???
What if... I told you that I didn't type that output, I copied and pasted it?