-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathexample.rb
More file actions
executable file
·119 lines (95 loc) · 2.32 KB
/
example.rb
File metadata and controls
executable file
·119 lines (95 loc) · 2.32 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#!/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 <<~EOC
unsigned long factorial_c(int max) {
int i=max, result=1;
while (i >= 2) { result *= i--; }
return result;
}
EOC
builder.c_raw <<~EOC
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);
}
EOC
# header isn't published but the function isn't static?
builder.prefix "VALUE rb_int_mul(VALUE x, VALUE y);"
builder.add_id "*"
builder.c <<~EOC
VALUE factorial_c_rb(int max) {
int i=max;
VALUE result = INT2NUM(1);
while (i >= 2) { result = rb_funcall(result, id_times, 1, INT2FIX(i--)); }
return result;
}
EOC
end
alias factorial_alias factorial_c_raw
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/ips'
puts "RubyInline #{Inline::VERSION}" if $DEBUG
t = MyTest.new
n = (ARGV.shift || 5).to_i
m = t.factorial n
warn "warning: N > 12 is prolly gonna fail on the C side" if n > 12
def validate n, m
raise "#{n} != #{m}" unless n == m
end
validate t.factorial_c_raw(n), m if n <= 12
validate t.factorial_c_rb(n), m
validate t.factorial_alias(n), m if n <= 12
validate t.factorial_c(n), m if n <= 12
validate t.factorial(n), m
puts "factorial(n = #{n}) = #{m}"
Benchmark.ips do |x|
x.config warmup: 1
x.report "null_time" do |max|
max.times do
# do nothing
end
end
x.report "c" do |max|
max.times do
t.factorial_c n
end
end if n <= 12
x.report "c-raw" do |max|
max.times do
t.factorial_c_raw n
end
end if n <= 12
x.report "c-alias" do |max|
max.times do
t.factorial_alias n
end
end if n <= 12
x.report "c-rb" do |max|
max.times do
t.factorial_c_rb n
end
end
x.report "pure ruby" do |max|
max.times do
t.factorial n
end
end
x.compare!
end