Python3调用vs生成的dll和Python3自身代码计算最大公约数时间对比

.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
分别调用.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代码并没有任何优势
计算1次公约数的执行时间,发现调用.dll和使用原生Python代码并没有任何优势
Tips:下面我就不贴代码了,将上述代码for循环中的range(1)变为range(10000)、range(1000000)、range(10000000)即可

公约数计算10000次

计算10000次公约数的执行时间,调用.dll的时间优势体现出来了,但是对于计算机来说60ms优势不算太明显
计算10000次公约数的执行时间,调用.dll的时间优势体现出来了,但是对于计算机来说60ms优势不算太明显

公约数计算100000次

时间差530ms
时间差530ms

公约数计算1000000次

时间差650ms
时间差650ms

公约数计算10000000次

这个时间差就明显了,6s
这个时间差就明显了,6s

结论

计算公约数是个很简单,很常见的算法,code执行次数不多的话,时间不算太长,若是百万级的执行次数,那执行时间也很长了,所以若是用Python开发项目,有计算量非常大的模块,用c++实现,再调用.dll库,在性能上是个不错的优化选择,而Python的c/c++接口主要的目的也是缘于计算量非常大的需求。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值