apt-get install libinline-ruby
gem install rubyinline
#! / 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
}
0.000000 0.000000 0.000000 (0.001326)
0.000000 0.000000 (0.000075)
Source: https://habr.com/ru/post/23976/
All Articles