.dll vs .py计算最大公约数执行时间对比
.dll文件对应的source code
.h文件
#pragma once
class test {
int gcd(int, int);
};
.cpp文件
#define DLLEXPORT extern "C" __declspec(dllexport)
#include "sample.h"
DLLEXPORT int gcd(int x, int y)
{
int g = y;
while (x > 0)
{
g = x;
x = y % x;
y = g;
}
return g;
}
.py对应的code和result
import ctypes
def hcf(x, y):
"""该函数返回两个数的最大公约数"""
# 获取最小值
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller + 1):
if ((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
x1 = 10
y1 = 10
x2 = ctypes.c_int(10)
y2 = ctypes.c_int(50)
dll = ctypes.CDLL('sample.dll')
result1 = hcf(x1, y1)
result2 = dll.gcd(x2, y2)
分别调用.dll和Python代码求10和50的最大公约数,从图中可以看出,结果是正确的,都是10
在code中加入计算执行时间的code
公约数计算1次
import ctypes
from time import time
def hcf(x, y):
"""该函数返回两个数的最大公约数"""
# 获取最小值
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller + 1):
if ((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
x1 = 10
y1 = 10
x2 = ctypes.c_int(10)
y2 = ctypes.c_int(50)
dll = ctypes.CDLL('sample.dll')
start1 = time()
for i in range(1):
result1 = hcf(x1, y1)
end1 = time()
start2 = time()
for i in range(1):
result2 = dll.gcd(x2, y2)
end2 = time()
print(end1 - start1, end2 - start2)
计算1次公约数的执行时间,发现调用.dll和使用原生Python代码并没有任何优势
Tips:下面我就不贴代码了,将上述代码for循环中的range(1)变为range(10000)、range(1000000)、range(10000000)即可
公约数计算10000次
计算10000次公约数的执行时间,调用.dll的时间优势体现出来了,但是对于计算机来说60ms优势不算太明显
公约数计算100000次
时间差530ms
公约数计算1000000次
时间差650ms
公约数计算10000000次
这个时间差就明显了,6s
结论
计算公约数是个很简单,很常见的算法,code执行次数不多的话,时间不算太长,若是百万级的执行次数,那执行时间也很长了,所以若是用Python开发项目,有计算量非常大的模块,用c++实现,再调用.dll库,在性能上是个不错的优化选择,而Python的c/c++接口主要的目的也是缘于计算量非常大的需求。