Software Architect, Father, Husband, Athlete
Text
So awhile back I first came across ruby benchmark when trying to learn how to use it in a RubyInline C example. The example shown below was a simple comparison of implementing factorial in Ruby vs Inline C. Now I know what your saying “Big surprise which one was faster right!”
require "rubygems"
require "benchmark"
require "inline"
class FactorialTest
def factorial_ruby(n)
result =1
n.downto(2){|x| result *= x}
result
end
inline do |builder|
builder.c "
long factorial_c(int max){
int i=max, result=1;
while(i >= 2){result *= i--;};
return result;
}"
end
end
t = FactorialTest.new()
Benchmark.bm do |x|
x.report(":factorial_ruby"){ t.factorial_ruby(50000) }
x.report(":factorial_c"){ t.factorial_c(50000) }
end
Results:
user system total real
:factorial_ruby 6.430000 0.590000 7.020000 (7.032876)
:factorial_c 0.000000 0.000000 0.000000 (0.000093)
Now the question you should be asking yourself is which version of ruby I was using when running this. The answer is Ruby 1.8.7. Now comes the fun, I thought hmmmm… wonder how the ruby factorial does in 1.9.2? Heres the results:
user system total real
:factorial_ruby 3.120000 0.020000 3.140000 (3.146494)
:factorial_c 0.000000 0.000000 0.000000 (0.000087)
WOW! I never expected to find that Ruby 1.9.2 was 2x’s faster that 1.8.7. This definitely had me asking more questions than my mind could answer. Since then I have been writing benchmarks for all sorts of code I had written and am quickly realizing what I was taught wasn’t code optimizing at all, it was code convoluting! But thats a whole other post.
I have included below some links for Ruby Benchmark, the RubyInline gem that allows awesome C extensions within ruby as well as a link to Antonio Cangiano’s post called “The Great Ruby Shootout (July 2010)” which has a wealth of information to absorb.
Text
It’s been a long time coming but my blog is finally up and I am ready to do this! ………… Now if only I had something to blog about??