Last active
September 20, 2017 06:29
-
-
Save bongole/a0393bb4f98fc5c129f9f51a411e1b16 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: