做這個小實驗的當天看到這個梗圖,相當呼應這個主題:
「其它的程式語言對你作力學是沒用的,作計算就三本柱 Python、C++、Fortran 足矣,連 C 都沒什麼用處。」Python在計算的速度上相較於C++非常的緩慢,這個demo很清楚地呈現了這件事。以計算力學為題,python在tool的開發,input的整合上具有優勢,但是在計算效能上的表現不佳,於是就有了許多與python互相支援的foreign function interface(FFI),如 swig, cython, pybind11。
截python所長,補C++所短 (or vice versa) ,似乎是做出更好的力學程式不可或缺的元素,pybind扮演的角色於是顯現。接下來就簡單用C++寫一個python的module:
1. 寫 .cpp/.h file。
#include <pybind11/pybind11.h>
double square(double i){
return i*i;
}
PYBIND11_MODULE(test, handle){ //Module 的attributes 會在這裡做定義
handle.doc()="This is my doc";
handle.def("sqrt", &square);
}
2. 寫 CMakeList.txt。
cmake_minimum_required(VERSION 3.4)
PROJECT(pybind_vid)
add_subdirectory(pybind11)
pybind11_add_module(test test.cpp) //test為建構的module的名稱 test.cpp是它所依據的檔案
3. Build the module。
mkdir build
cd build/
cmake ..
make
4. 在python中使用前面所建立的module。
~/git-repo/importation/test$ python3
>>> import test
>>> dir(test)
['doc', 'file', 'loader', 'name', 'package', 'spec', 'sqrt']
>>> test.sqrt(3.145)
9.891025
>>> test.__doc__
"This is my doc"
- dir(test)中可以看我們define的function以及attributes。
- What's the cause of success within ~/git-repo/importation/test but not ~/git-repo/importation?
>>> import test
>>> dir(test)
['builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec']
留言
張貼留言