Speed up your Ruby Code

Ever wish you could embed C code directly in Ruby? Me neither, but sometimes you have to take one for the team in order to speed up your code. RubyInline allows you to do exactly that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

class MyTest

  def factorial(n)
    f = 1
    n.downto(2) { |x| f *= x }
    f
  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

For a full guide on optimizing Ruby code including profiling, benchmarking, and using RubyInline, please check out this tutorial


About this entry