In the process of using ruby/rails, it is found that sometimes performance is unsatisfactory, such as the generation of a 3-layer tree with 600 items of the directory to spend 20ms, in order to improve performance in the learning to write Ruby module with C + +, the understanding of the Swig, Rubyinline a series of assistive tools that help you write C/A + + to improve ruby performance.
Rubyinline is used in the embedded C + + program, simple and quick, and Swig helps us to write independent Ruby modules more easily with C + +.
How to get started with swig
Goal: Write a ruby module test with swig/c++, and provide the Add method for addition operations.
Related documents:
(1). TEST.I interface
(2). test.h header File
(3). Test.cxx function Implementation
(4). EXTCONF.RB used to generate makefile
(5). (automatic) Test_wrap.cxx Swig generated test encapsulation
(6). Automatically Makefile Makefile files are obtained by Ruby EXTCONF.RB
(7). (automatic) test.so Ruby modules are available from make
1, establish the interface file test.i
Copy Code code as follows:
%module Test
%{
Include header file
#include "test.h"
%}
Interface add
int add (int,int);
2, the preparation of wrap documents
Copy Code code as follows:
Get Test Package file Test_wrap.cxx
3, the preparation of test.h and Test.cxx
Copy Code code as follows:
Test.h
#ifndef _test_test_h
#define _test_test_h
extern int Add (int,int);
#endif
Test.cxx
#include "test.h"
int add (int left,int right)
{
return left+right;
}
4, write extconf.rb for the rapid generation of makefile
Copy Code code as follows:
Require ' MKMF '
Dir_config ' Test '
#stdc + + library, the Add function is not used
$libs = Append_library $libs, ' stdc++ '
Create_makefile ' Test '
Run Ruby extconf.rb get Makefile file
5. Generate Test Module
Run make to get module test.so
6, testing
Copy Code code as follows:
Irb
IRB (main):001:0> require ' test '
=> true
IRB (main):002:0> Test.add 3,4
=> 7
IRB (main):003:0> Test.add 3333333333333333333333,44444444444444444
typeerror:expected argument 0 of type int, but got bignum 3333333333333333333333
In SWIG method ' add '
From (IRB): 3:in ' Add '
From (IRB): 3
from:0
IRB (main):004:0>
Test successful
7, Swig
Swig supports many of the advanced features of C + + to write Ruby modules, such as classes, inheritance, overloads, templates, STL, and so on.
8. RELATED LINKS
(1). Swig
(2). Swig/ruby Document
9, Notes
The Add function in this article is too simple to compare the performance of Ruby 3+4 down.