9. LIBFFI
http://sourceware.org/libffi/
“A foreign function interface is the
popular name for the interface that
allows code written in one language
to call code written in another
language.”
10. e
m
i
Application
t
n
uses
u
libsomething_foo()
R FFI
libsomething.so
12. 1 #ifndef __SIMPLE_METRICS_H__
2 #define __SIMPLE_METRICS_H__
3 #include <stdlib.h>
4 #include <math.h>
5
6 typedef struct _simple_metrics{
7 double min;
8 double max;
9 double sum;
10 double sumsq;
11 long count;
12 } simple_metrics ;
13
14 simple_metrics* simple_metrics_new();
15 void simple_metrics_free( simple_metrics* sm );
16 void simple_metrics_update( simple_metrics* sm, double value );
17 double simple_metrics_mean( simple_metrics* sm );
18 double simple_metrics_min( simple_metrics* sm );
19 double simple_metrics_max( simple_metrics* sm );
20 double simple_metrics_sum( simple_metrics* sm );
21 long simple_metrics_count( simple_metrics* sm );
22 double simple_metrics_stddev( simple_metrics* sm );
23 double simple_metrics_rate( simple_metrics* sm );
24
25 #endif
13. 1 class Metric
2 attr_reader :name
3 def initialize( name )
4 @name
5 end
6
7 def update( new_value) ... end
8 def count ... end
9 def max ... end
10 def mean ... end
11 def min ... end
12 def rate ... end
13 def sum ... end
14 def stddev ... end
15 end
16. 35 module SimpleMetrics
36 module FFI
37 class Metric < ::SimpleMetrics::Common
38 include ::SimpleMetrics::FFI
39 def initialize( name )
40 super
41 @impl = FFI.simple_metrics_new
42 end
43
44 def update( v )
45 simple_metrics_update( @impl, v )
46 end
47
48 self.keys.each do |f|
49 module_eval <<-code
50 def #{f}
51 simple_metrics_#{f}( @impl )
52 end
53 code
54 end
55 end
56 end
57 end
19. MEANINGLESS METRICS
Traditional C
FFI
Extension
Jeremy’s Time 40 minutes 70 minutes
1 Million update()
1.16 sec 0.42 sec
calls
Will it Blend run
Yes No
on JRuby?
20. % ruby ~/Projects/simple_metrics/example/bench.rb 1000000
generating 1000000 random numbers between 0 and 10,000
Rehearsal -----------------------------------------------
ext 0.420000 0.000000 0.420000 ( 0.460806)
ffi 1.160000 0.000000 1.160000 ( 1.171498)
-------------------------------------- total: 1.580000sec
user system total real
ext 0.420000 0.010000 0.430000 ( 0.424809)
ffi 1.160000 0.000000 1.160000 ( 1.182928)
% ./bin/jruby ~/Projects/simple_metrics/example/bench.rb 1000000
generating 1000000 random numbers between 0 and 10,000
Skipping Ext
Rehearsal -----------------------------------------------
ffi 0.922000 0.000000 0.922000 ( 0.922000)
-------------------------------------- total: 0.922000sec
user system total real
ffi 0.834000 0.000000 0.834000 ( 0.834000)
24. THANKS
• Wayne Meissner - adding libffi to JRuby and providing the
ffi gem for MRI.
• Evan Phoenix - using libffi in Rubinius
• Authors of the examples on the Project Kenai wiki