python windows和linux运算速度_linux、windows环境下用C++改善python运算效率

Linux:

同一运算的 C++ 和 python 实现:

C++:

python:

上述示例代码 python 的运算速度要比 C++ 慢 50 倍(C++编译未优化的情况下)。

一、生成 C++ so。

目录结构如下:

---------------

| -- pythonso.h

| -- pythonso.cpp

| -- pythonso.so(通过g++编译生成)

| -- test.py

pythonso.h

#ifdef __cplusplus

extern "C" {

long int step(int);

char* concat(char*, char*);

}

#endif

pythonso.cpp

#include

#include "pythonso.h"

long int _step(int x) {

if (x == 1 || x == 2) {

return x;

}

else {

return _step(x - 1) + _step(x - 2);

}

}

long int step(int x){

return _step(x);

}

char* concat(char* a, char* b){

std::string x(a), y(b);

char* c = const_cast((x + y).c_str());

return c;

}

运行命令行参数,在当前目录生成pythonso.so文件。

g++ -fPIC -shared ./pythonso.cpp -o ./pythonso.so

二、用 python 调用刚生成的 pythondso.so。

test.py

import time

from ctypes import cdll, c_int, c_char_p

cso = cdll.LoadLibrary("./pythonso.so")

if __name__ == '__main__':

start = time.time()

n = cso.step(c_int(45))

end = time.time()

print(f"耗时:{end - start},结果:{n}")

cso.concat.restype = c_char_p

string = cso.concat(c_char_p(b"asd"), c_char_p(b"123"))

print("连接两个字符串的结果:{}".format(string.decode("utf-8")))

运行结果:

Windows:

同一运算的 C++ 和 python 实现:

C++:

python:

上述示例代码 python 的运算速度要比 C++ 慢 100 倍。

一、生成 C++ dll。

目录结构如下:

pythondll.def

LIBRARY

EXPORTS

;step函数

step

;concat函数

concat

pythondll.h

extern "C" {

_declspec(dllexport) long int step(int);

_declspec(dllexport) char* concat(char*, char*);

}

pythondll.cpp

#include

long int step(int x){

if (x == 1 || x == 2) {

return x;

}

else {

return step(x - 1) + step(x - 2);

}

}

char* concat(char* a, char* b){

std::string x(a), y(b);

char* c = const_cast((x + y).c_str());

return c;

}

然后设置配置类型为 dll

完成上述操作,即可生成 pythondll.dll。

二、用 python 调用刚生成的 pythondll.dll。

test.py

import time

from ctypes import CDLL, c_int, c_char_p

cdll = CDLL("./pythondll.dll")

if __name__ == '__main__':

start = time.time()

n = cdll.step(c_int(45))

end = time.time()

print(f"耗时:{end - start},结果:{n}")

cdll.concat.restype = c_char_p

string = cdll.concat(c_char_p(b"asd"), c_char_p(b"123"))

print("连接两个字符串的结果:{}".format(string.decode("utf-8")))

运行结果:

可见,对于一些耗时较多的运算,可以改用 C++ 来写,以此改善 python 运算效率。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值