« Back to Index

Example code using RubyInline which lets you run foreign code (such as C or C++) within Ruby which has much greater performance over Ruby itself.

View original Gist on GitHub

RubyInline.rb

#!/usr/bin/env ruby

# gem install RubyInline

require 'inline'
require 'benchmark'

class Fixnum
    def factorial
        (1..self).inject { |a, b| a * b }
    end
end

class CFactorial
    inline do |builder|
        builder.c_singleton %q{
            long factorial(int value) {
                long result = 1, i = 1;
                for (i = 1; i <= value; i++) {
                    result *= i;
                }
                return result;
            }
        }
    end
end

Benchmark.bm do |bm|
    bm.report('ruby:') do
        100000.times { 8.factorial }
    end

    bm.report('c:') do
        100000.times { CFactorial.factorial(8) }
    end
end