Inlining C code in Ruby

Tags:

http://on-ruby.blogspot.com/2006/07/rubyinline-making-making-things-faster.html

C 코드를 Ruby에 inlining하는 방법입니다. 먼저 inline gem 설치.

mkseo@mkseo:~/tmp$ sudo gem install rubyinline
Attempting local installation of 'rubyinline'
Local gem file not found: rubyinline*.gem
Attempting remote installation of 'rubyinline'
Successfully installed RubyInline-3.5.0
mkseo@mkseo:~/tmp$

테스트 코드.

require “rubygems”
require “inline”

class RubyInlinePrime
inline do |builder|
builder.c ”
int prime(int n)
{
int x;
if (n == 2) return 1;
for (x = 2; x < n - 1; x++) if (n % x == 0) return x; return 1; }" end end class RubyNativePrime def prime(n) return 1 if n == 2 for x in (2..n-1) return x if n % x == 0 end return 1; end end ruby_time = Time.now nav_prime = RubyNativePrime.new 2.upto(10000) do |i| if nav_prime.prime(i) != 1 puts "#{i} is #{nav_prime.prime(i)} * #{i / nav_prime.prime(i)}" else puts "#{i} is a prime number." end end ruby_time = Time.now - ruby_time c_time = Time.now c_prime = RubyInlinePrime.new 2.upto(10000) do |i| if c_prime.prime(i) != 1 puts "#{i} is #{c_prime.prime(i)} * #{i / c_prime.prime(i)}" else puts "#{i} is a prime number." end end c_time = Time.now - c_time puts "Ruby: #{ruby_time}" puts "Inlining C: #{c_time}" [/code] 실행 결과 [code] mkseo@mkseo:~/tmp$ ruby test_inline.rb | tail 9993 is 3 * 3331 9994 is 2 * 4997 9995 is 5 * 1999 9996 is 2 * 4998 9997 is 13 * 769 9998 is 2 * 4999 9999 is 3 * 3333 10000 is 2 * 5000 Ruby: 13.717828 Inlining C: 0.301906 mkseo@mkseo:~/tmp$ [/code] 물론 루비를 먼저 실행하냐, C를 먼저 실행하냐, 몇번 반복하냐 등에 따라 실험결과는 달라지지만 13.7초 vs 0.3 초는 이런 비난이 가해질 수 없는 성능 차. 사실 저도 최근에 루비로 된 코드를 C++로 포팅한뒤 33배 성능이 향상되는 바람에 루비에 좌절. 루비가 최근 작은 사이즈에서는 does not scale well 이라는 말이 나오는데 근거 없는 말이 절대로 아님.. CPU Intesive 한 경우에는 이런 극적인 차가 더 잘 드러납니다. 그러니까, Ruby off the rails sucks?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *