在使用ruby/rails的過程中,確實發(fā)現(xiàn)有時性能不盡人意,如生成一個擁有600項的item的3層樹形結(jié)構(gòu)目錄要花去20ms,為提高性能在學習用c/c++寫ruby模塊的過程中,認識了swig,rubyInline等一系列幫助編寫c/c++來提升ruby性能的輔助工具。
rubyInline用于內(nèi)嵌c/c++程序,簡單快捷,swig則幫助我們更容易地用c/c++寫出獨立的ruby模塊。
swig的入門使用方法
目標:用swig/c++編寫一個ruby模塊Test,并提供add方法作加法運算。
相關(guān)文件:
(1).test.i 接口
(2).test.h 頭文件
(3).test.cxx 函數(shù)實現(xiàn)
(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函數(shù)未用到
$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、相關(guān)鏈接
(1).swig
(2).swig/ruby 文檔
9、備注
本文的add函數(shù)過于簡單,對比ruby 3+4性能不升反降。
您可能感興趣的文章:- Ruby中的block代碼塊學習教程
- 詳解Ruby中的代碼塊對象Proc
- Ruby中編寫類與模塊的風格指南
- Ruby中關(guān)于模塊的一些基礎(chǔ)知識
- 介紹Ruby中的模塊與混合類型的相關(guān)知識
- 詳解Ruby中的塊的知識
- 使用Ruby re模塊創(chuàng)建復雜的正則表達式
- ruby 模塊
- 深入理解Ruby中的代碼塊block特性