RubyInlineがすごい
Rubyコード中にCのコードを埋め込めるRubyInlineを使って、 ボトルネックとなっているメソッドを置き換える。
# rubyinline.rb
def benchmark
s = "a" * 10000
test = Test.new
t = Time.now
1000.times{test.string_xor(s, s)}
Time.now - t
end
class Test
def string_xor(str1, str2)
result = str1.clone
str1.length.times do |i|
result[i] ^= str2[i]
end
result
end
end
b1 = benchmark
begin
require 'inline'
class Test
inline do |builder|
builder.c <<-EOF
VALUE
string_xor(VALUE str1, VALUE str2)
{
VALUE result = rb_str_new(RSTRING(str1)->ptr, RSTRING(str1)->len);
int i;
for (i = 0; i < RSTRING(str1)->len; i++) {
RSTRING(result)->ptr[i] ^= RSTRING(str2)->ptr[i];
}
return result;
}
EOF
end
end
rescue LoadError
end
b2 = benchmark
p b1/b2長さ10000の文字列同士のxorを1000回取る、というプログラムでテスト。
$ ruby -rubygems rubyinline.rb 192.710154532523
192倍!
2007/4/6 追記:
そういえば、GCを切るのを忘れていたと思って、GC無しで実行したら、300倍になった。
参考:
Mon, 12 Mar 2007 14:14 カテゴリ tech, ruby
タグ c, ruby, rubyinline
0 comments »
〜へのトラックバック RubyInlineがすごい
-
perlにも昔からInline::Cというモジュールがありましたが、こちらの事例ではご利益にあずかれません。 netswitch! | RubyInlineがすごい長さ10000の文字列同士のxorを1000回取る、というプログラ...