怎么在python中利用Eigen对代码进行加速

发布时间:2020-12-07 14:21:07 作者:Leah
来源:亿速云 阅读:465

这期内容当中小编将会给大家带来有关怎么在python中利用Eigen对代码进行加速,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

第一步:准备系统和IDE:

Windows 10 
vs2015 (用于调试c++代码)
vscode (调试python代码)

第二步:python虚拟环境:

1.创建虚拟python虚拟环境: 在vscode的terminal中执行 

python -m venv env

2.下载 Eigen: 将Eigen解压到当前目录命名为 eigen-3.3.8
3.在vscode的terminal中激活虚拟环境:

 ./env/Scripts/Activate.ps1

怎么在python中利用Eigen对代码进行加速

4.安装pybind11:

pip install pybind11

5.安装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" 函数。程序执行将在此处开始并结束。
//
#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中使用的函数名*/, &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])

第六步:编译测试

怎么在python中利用Eigen对代码进行加速

注意:我的cpp_python.cpp和setup.py是在同一个文件夹下。

执行: "python .\setup.py build_ext --inplace"就会得下面的结果,生成.pyd文件表明我们已经编译成功。

怎么在python中利用Eigen对代码进行加速

运行测试:

怎么在python中利用Eigen对代码进行加速

上述就是小编为大家分享的怎么在python中利用Eigen对代码进行加速了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么在python中利用SVD对图像进行压缩
  2. 怎么在Python中利用opencv对图像阈值进行处理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python eigen

上一篇:JavaScript模块规范中CommonJS、AMD和CMD是什么意思

下一篇:浏览器输入url到发起http请求的案例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》