在使用ruby/rails的過程中,確實發現有時效能不盡人意,如產生一個擁有600項的item的3層樹形結構目錄要花去20ms,為提高效能在學慣用c/c++寫ruby模組的過程中,認識了swig,rubyInline等一系列協助編寫c/c++來提升ruby效能的協助工具輔助。
rubyInline用於內嵌c/c++程式,簡單快捷,swig則協助我們更容易地用c/c++寫出獨立的ruby模組。
swig的入門使用方法
目標:用swig/c++編寫一個ruby模組Test,並提供add方法作加法運算。
相關檔案:
(1).test.i 介面
(2).test.h 標頭檔
(3).test.cxx 函數實現
(4).extconf.rb 用於產生makefile
(5).(自動)test_wrap.cxx swig產生的test封裝
(6).(自動)Makefile Makefile檔案由ruby extconf.rb得到
(7).(自動)test.so ruby模組 由make得到
1、建立介面檔案test.i
複製代碼 代碼如下:
%module test
%{
//包含標頭檔
#include "test.h"
%}
//介面add
int add(int,int);
2、編寫wrap檔案
複製代碼 代碼如下:
swig -c++ -ruby test.i
得到test封裝檔案test_wrap.cxx
3、編寫test.h與test.cxx
複製代碼 代碼如下:
//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、編寫extconf.rb用於快速產生makefile
複製代碼 代碼如下:
require 'mkmf'
dir_config 'test'
#stdc++庫,add函數未用到
$libs = append_library $libs,'stdc++'
create_makefile 'test'
運行 ruby extconf.rb 得到 Makefile 檔案
5、產生test模組
運行 make 得到模組 test.so
6、測試
複製代碼 代碼如下:
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>
測試成功
7、swig
swig支援很多c++的進階特性來編寫ruby的模組,如類,繼承,重載,模板,stl等。
8、相關連結
(1).swig
(2).swig/ruby 文檔
9、備忘
本文的add函數過於簡單,對比ruby 3+4效能不升反降。