If you are like me and somewhat offended by joel’s post a while back on ruby performance then RubyInline is for you. He also has another product called ruby2c but I haven’t tried it yet.
Basically, RubyInline lets you put other code inside of a ruby class and it will be compiled and called dynamically from the ruby code. Right now it only supports c and c++.
Here is a trivial example of a class that has 2 methods one in ruby and one in c. They both loop from 1 to 1,000,000 each time calling “i * i” and saving it in a variable x:
require 'rubygems'
require 'inline'
require 'benchmark'
class FastClass
def ruby_loop
1.upto 1000000 do |i|
x = i * i
end
end
inline(:C) do |builder|
builder.add_compile_flags '-x c++', '-lstdc++'
builder.c '
void c_loop() {
int i = 1;
while (i++ <= 1000000) {
long x = i * i;
}
}'
end
end
fc = FastClass.new
Benchmark.bm(10) do |b|
b.report('ruby') { fc.ruby_loop }
b.report('c') { fc.c_loop }
end
you can see from the benchmark stats that c is WAY faster:
user system total real
ruby 4.790000 0.130000 4.920000 ( 5.950551)
c 0.010000 0.000000 0.010000 ( 0.001360)
Feel free to use this technique on a highly computational portion of code that appears to be a bottle neck.