Skip to content

Instantly share code, notes, and snippets.

@bongole
Last active September 20, 2017 06:29
Show Gist options
  • Save bongole/a0393bb4f98fc5c129f9f51a411e1b16 to your computer and use it in GitHub Desktop.
Save bongole/a0393bb4f98fc5c129f9f51a411e1b16 to your computer and use it in GitHub Desktop.
require 'ffi'
require 'fiddle'
require 'benchmark'
def setup
open("/tmp/test.c","w") do |io|
c_src = <<-EOS
int add(int a, int b){
return a + b;
}
int add2(int a, int b){
return a + b;
}
EOS
io.print(c_src)
end
`gcc -shared /tmp/test.c -o /tmp/libtest.so`
end
setup
LIB_PATH= "/tmp/libtest.so"
module FFILib
extend FFI::Library
ffi_lib LIB_PATH
attach_function :add, [ :int, :int ], :int, :blocking => false
attach_function :add2, [ :int, :int ], :int, :blocking => true
end
lib = Fiddle.dlopen(LIB_PATH)
fiddle_add = Fiddle::Function.new(
lib['add'], [Fiddle::TYPE_INT, Fiddle::TYPE_INT], Fiddle::TYPE_INT
)
p 3 == fiddle_add.call(1,2)
p 3 == FFILib.add(1,2)
p 3 == FFILib.add2(1,2)
n=1000000
Benchmark.bmbm(10) do |x|
x.report("fiddle") { n.times{ fiddle_add.call(1,1) }}
x.report("ffi-nonblocking"){ n.times{ FFILib.add(1,1) }}
x.report("ffi-blocking"){ n.times{ FFILib.add2(1,1) }}
end
@bongole
Copy link
Author

bongole commented Sep 20, 2017

Output:

true
true
true
Rehearsal ---------------------------------------------------
fiddle            1.000000   0.170000   1.170000 (  1.166142)
ffi-nonblocking   0.140000   0.000000   0.140000 (  0.143218)
ffi-blocking      0.450000   0.170000   0.620000 (  0.615898)
------------------------------------------ total: 1.930000sec

                      user     system      total        real
fiddle            0.980000   0.170000   1.150000 (  1.143717)
ffi-nonblocking   0.130000   0.000000   0.130000 (  0.132647)
ffi-blocking      0.450000   0.160000   0.610000 (  0.618110)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment