python 通過 pybind11 使用Eigen加速代碼的步驟
python是很容易上手的編程語言,但是有些時(shí)候使用python編寫的程序并不能保證其運(yùn)行速度(例如:while 和 for),這個(gè)時(shí)候我們就需要借助c++等為我們的代碼提速。下面是我使用pybind11調(diào)用c++的Eigen庫(kù)的簡(jiǎn)單介紹:
第一步:準(zhǔn)備系統(tǒng)和IDE:
Windows 10 vs2015 (用于調(diào)試c++代碼)vscode (調(diào)試python代碼)
第二步:python虛擬環(huán)境:
1.創(chuàng)建虛擬python虛擬環(huán)境: 在vscode的terminal中執(zhí)行
python -m venv env
2.下載 Eigen: 將Eigen解壓到當(dāng)前目錄命名為 eigen-3.3.83.在vscode的terminal中激活虛擬環(huán)境:
./env/Scripts/Activate.ps1
4.安裝pybind11:
pip install pybind11
5.安裝numpy==1.19.3(使用1.19.4可能會(huì)有問題)
pip install numpy==1.19.3
第三步:使用vs2015編寫cpp_python.cpp, 并保證沒有bug
#include <Eigen/Dense>using namespace stdusing namespace EigenMatrixXd add_mat(MatrixXd A_mat, MatrixXd B_mat){ return A_mat + B_mat;}
第四步:使用pybind11為cpp_python.cpp添加python接口
// cpp_python.cpp : 此文件包含 'main' 函數(shù)。程序執(zhí)行將在此處開始并結(jié)束。//#include <pybind11/pybind11.h>#include <pybind11/eigen.h>#include<pybind11/numpy.h>#include<fstream>#include<iostream>#include <Eigen/Dense>using namespace std;using namespace Eigen; MatrixXd add_mat(MatrixXd A_mat, MatrixXd B_mat){ return A_mat + B_mat;} namespace py = pybind11;PYBIND11_MODULE(add_mat_moudle, m){ m.doc() = 'Matrix add';//解釋說明 m.def('mat_add_py'/*在pyhon中使用的函數(shù)名*/, &add_mat);}
第五步:設(shè)置setup.py用來編譯c++代碼
from setuptools import setupfrom setuptools import Extensionadd_mat_module = Extension(name=’add_mat_moudle’, # 模塊名稱 sources=[’cpp_python.cpp’], # 源碼 include_dirs=[r’.eigen-3.3.8’, r’.envScripts’, # 依賴的第三方庫(kù)的頭文件 r’.envLibsite-packagespybind11include’] )setup(ext_modules=[add_mat_module])
第六步:編譯測(cè)試
注意:我的cpp_python.cpp和setup.py是在同一個(gè)文件夾下。
執(zhí)行: 'python .setup.py build_ext --inplace'就會(huì)得下面的結(jié)果,生成.pyd文件表明我們已經(jīng)編譯成功。
運(yùn)行測(cè)試:
以上就是python 通過 pybind11 使用Eigen加速代碼的步驟的詳細(xì)內(nèi)容,更多關(guān)于python 加速代碼的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項(xiàng)目的過程2. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp3. php測(cè)試程序運(yùn)行速度和頁面執(zhí)行速度的代碼4. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究5. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析6. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁7. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問題分析8. ASP中常用的22個(gè)FSO文件操作函數(shù)整理9. SharePoint Server 2019新特性介紹10. 三個(gè)不常見的 HTML5 實(shí)用新特性簡(jiǎn)介
