Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Using RubyInline to Speed Up Code By 10x

By Peter Cooper / July 27, 2006

After writing a basic routine to print all prime numbers between 1 and 10,000 in Ruby, Pat Eyler found it took almost 3 seconds to complete, and seeked out a way to make it faster. Enter RubyInline (covered previous at RubyInside).. With RubyInline he added a basic C function into the Ruby mix and knocked down the time required to 0.3 seconds.

The code:

require "rubygems"
require "inline"

class Primes
  inline do |builder|
    builder.c '
    int prime(int num) {
      int x;
      for (x = 2; x < (num - 1) ; x++) {
        if (num == 2) {
          return 1;
        }
        if (num % x == 0) {
          return x;
        }
      }
      return 1;
    }'
  end
end

p = Primes.new

for num in 2..10_000 do
  is_prime = p.prime(num)
  if is_prime == 1
    puts "#{num} is a prime number"
  else
    puts "#{num} equals #{is_prime} * #{num/is_prime}"
  end
end

Read more.. (found via ozmm)

Comments

  1. Anonomous Grammar Police says:

    Ahem...

    "seeked" => sought

  2. Danno says:

    I dunno if ZenSpider is still working on this or not, but it presents an even better sort of solution: http://www.zenspider.com/ZSS/Products/RubyInline/index.html

  3. Pat Eyler says:

    Umm, Danno, I used zenspiders RubyInline to do this, so I'm not sure you can call it better. ;^)

  4. Dave Andersen says:

    While I realize that the author was working under the constraint of "someone forced me to use this algorithm to keep things consistent", this is an agonizing example of "optimize the algorithm, not the implementation." Instead of using C, a complex package that shells out to gcc, and writing code that's 3x longer than it needs to be, rewriting the algorithm to use the Sieve -- in pure ruby -- takes the runtime down to 0.1 seconds (1/3rd of the time required by the Inline C version):

    http://dga.livejournal.com/22232.html

    Let's stomp out this terrible, terrible example and not leave the net scattered with bad examples of optimizing the wrong way.

Other Posts to Enjoy

Twitter Mentions