Using RubyInline to Speed Up Code By 10x

By Peter Cooper

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)