python3 通過 pybind11 使用Eigen加速代碼的步驟詳解
python是很容易上手的編程語言,但是有些時候使用python編寫的程序并不能保證其運行速度(例如:while 和 for),這個時候我們就需要借助c++等為我們的代碼提速。下面是我使用pybind11調用c++的Eigen庫的簡單介紹:
第一步:準備系統(tǒng)和IDE:
- Windows 10
- vs2015 (用于調試c++代碼)
- vscode (調試python代碼)
第二步:python虛擬環(huán)境:
1.創(chuàng)建虛擬python虛擬環(huán)境: 在vscode的terminal中執(zhí)行
python -m venv env
2.下載 Eigen : 將Eigen解壓到當前目錄命名為 eigen-3.3.8
3.在vscode的terminal中激活虛擬環(huán)境:
./env/Scripts/Activate.ps1
4.安裝pybind11:
pip install pybind11
安裝numpy==1.19.3(使用1.19.4可能會有問題) :
pip install numpy==1.19.3
第三步:使用vs2015編寫cpp_python.cpp, 并保證沒有bug
#include <Eigen/Dense>
using namespace std
using namespace Eigen
MatrixXd add_mat(MatrixXd A_mat, MatrixXd B_mat)
{
return A_mat + B_mat;
}
第四步:使用pybind11為cpp_python.cpp添加python接口
// cpp_python.cpp : 此文件包含 "main" 函數(shù)。程序執(zhí)行將在此處開始并結束。
//
#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);
}
第五步:設置setup.py用來編譯c++代碼
from setuptools import setup
from setuptools import Extension
add_mat_module = Extension(name='add_mat_moudle', # 模塊名稱
sources=['cpp_python.cpp'], # 源碼
include_dirs=[r'.\eigen-3.3.8',
r'.\env\Scripts', # 依賴的第三方庫的頭文件
r'.\env\Lib\site-packages\pybind11\include']
)
setup(ext_modules=[add_mat_module])
第六步:編譯測試
這是我當前的工作目錄

注意:我的cpp_python.cpp和setup.py是在同一個文件夾下。
執(zhí)行: "python .\setup.py build_ext --inplace"就會得下面的結果,生成.pyd文件表明我們已經編譯成功。

運行測試:

到此這篇關于python3 通過 pybind11 使用Eigen加速代碼的步驟詳解的文章就介紹到這了,更多相關python3 pybind11 Eigen加速代碼內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python操作PostgreSQL數(shù)據(jù)庫的基本方法(增刪改查)
PostgreSQL數(shù)據(jù)庫是最常用的關系型數(shù)據(jù)庫之一,最吸引人的一點是它作為開源數(shù)據(jù)庫且具有可拓展性,能夠提供豐富的應用,這篇文章主要給大家介紹了關于Python操作PostgreSQL數(shù)據(jù)庫的基本方法,文中介紹了連接PostgreSQL數(shù)據(jù)庫,以及增刪改查,需要的朋友可以參考下2023-09-09
flask操作數(shù)據(jù)庫插件Flask-SQLAlchemy的使用
Python?中最廣泛使用的ORM框架是SQLAlchemy,它是一個很強大的關系型數(shù)據(jù)庫框架,本文就來介紹一下flask操作數(shù)據(jù)庫插件Flask-SQLAlchemy的使用,感興趣的可以了解一下2023-09-09
Python 如何創(chuàng)建一個簡單的REST接口
這篇文章主要介紹了Python 如何創(chuàng)建一個簡單的REST接口,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下2020-07-07

