-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
example.rb
executable file
·86 lines (70 loc) · 1.58 KB
/
example.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/local/bin/ruby -w
require 'rubygems'
$:.unshift 'lib'
require 'inline'
require 'fileutils'
FileUtils.rm_rf File.expand_path("~/.ruby_inline")
class MyTest
def factorial(n)
f = 1
n.downto(2) { |x| f *= x }
f
end
inline do |builder|
builder.c "
long factorial_c(int max) {
int i=max, result=1;
while (i >= 2) { result *= i--; }
return result;
}"
builder.c_raw "
static
VALUE
factorial_c_raw(int argc, VALUE *argv, VALUE self) {
int i=FIX2INT(argv[0]), result=1;
while (i >= 2) { result *= i--; }
return INT2NUM(result);
}"
end
end
# breakeven for build run vs native doing 5 factorial:
# on a PIII/750 running FreeBSD: about 5000
# on a PPC/G4/800 running Mac OSX 10.2: always faster
require 'benchmark'
puts "RubyInline #{Inline::VERSION}" if $DEBUG
MyTest.send(:alias_method, :factorial_alias, :factorial_c_raw)
t = MyTest.new()
max = (ARGV.shift || 1_000_000).to_i
n = (ARGV.shift || 5).to_i
m = t.factorial(n)
def validate(n, m)
if n != m then raise "#{n} != #{m}"; end
end
puts "# of iterations = #{max}, n = #{n}"
Benchmark::bm(20) do |x|
x.report("null_time") do
max.times do
# do nothing
end
end
x.report("c") do
max.times do
validate(t.factorial_c(n), m)
end
end
x.report("c-raw") do
max.times do
validate(t.factorial_c_raw(n), m)
end
end
x.report("c-alias") do
max.times do
validate(t.factorial_alias(n), m)
end
end
x.report("pure ruby") do
max.times do
validate(t.factorial(n), m)
end
end
end