📜 ⬆️ ⬇️

Ruby inline

Today it was necessary to add a small “number crusher” to the Ruby project. Quickly implemented the code, tested it, but was horrified by the performance. I remembered the inline module. The meaning of which is to compile the C code, and dynamically connect it to the Ruby program. It happens transparently.
To do this, you must install the library:
Debian-way:
apt-get install libinline-ruby

RubyGem:
gem install rubyinline

I will show the example of Fibonacci numbers:

#! / usr / bin / ruby ​​-w

require 'rubygems'
require 'inline'
require 'benchmark'
')
class Example
def fib (n)
curr = 0
succ = 1
n.times do | i |
curr, succ = succ, curr + succ
end
return curr
end

inline (: C) do | builder |
builder.c "
unsigned long fastfib (unsigned long n)
{
unsigned int n0 = 0;
unsigned int n1 = 1;
unsigned int naux;
unsigned int i;
if (n == 0)
return 0;
for (i = 0; i <n-1; i ++) {
naux = n1;
n1 = n0 + n1;
n0 = naux;
}
return n1;
}
"
end
end

t = Example.new;

puts Benchmark.measure {
40.times do | i |
t.fib i
end
}

puts Benchmark.measure {
40.times do | i |
t.fastfib i
end
}

Result on the face:

0.000000 0.000000 0.000000 (0.001326)
0.000000 0.000000 (0.000075)


Of course, using the inline-compilation the very first run will be longer - in the future, the code is cached

PS: transfer to Ruby blog

Source: https://habr.com/ru/post/23976/


All Articles