gpt4 book ai didi

python - 纯 Python 比 Numpy 更快?我可以使这个 numpy 代码更快吗?

转载 作者:太空狗 更新时间:2023-10-30 01:51:45 27 4
gpt4 key购买 nike

我需要根据特定的面/顶点列表计算最小值、最大值和平均值。我尝试使用 Numpy 优化此计算,但没有成功。

这是我的测试用例:

#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
'''
Module Started 22 févr. 2013
@note: test case comparaison numpy vs python
@author: Python4D/damien
'''

import numpy as np
import time


def Fnumpy(vertices):
np_vertices=np.array(vertices)
_x=np_vertices[:,:,0]
_y=np_vertices[:,:,1]
_z=np_vertices[:,:,2]
_min=[np.min(_x),np.min(_y),np.min(_z)]
_max=[np.max(_x),np.max(_y),np.max(_z)]
_mean=[np.mean(_x),np.mean(_y),np.mean(_z)]
return _mean,_max,_min

def Fpython(vertices):
list_x=[item[0] for sublist in vertices for item in sublist]
list_y=[item[1] for sublist in vertices for item in sublist]
list_z=[item[2] for sublist in vertices for item in sublist]
taille=len(list_x)
_mean=[sum(list_x)/taille,sum(list_y)/taille,sum(list_z)/taille]
_max=[max(list_x),max(list_y),max(list_z)]
_min=[min(list_x),min(list_y),min(list_z)]
return _mean,_max,_min

if __name__=="__main__":
vertices=[[[1.1,2.2,3.3,4.4]]*4]*1000000
_t=time.clock()
print ">>NUMPY >>{} for {}s.".format(Fnumpy(vertices),time.clock()-_t)
_t=time.clock()
print ">>PYTHON>>{} for {}s.".format(Fpython(vertices),time.clock()-_t)

结果是:

Numpy:

([1.1000000000452519, 2.2000000000905038, 3.3000000001880174], [1.1000000000000001, 2.2000000000000002, 3.2999999999999998], [1.1000000000000001, 2.2000000000000002, 3.2999999999999998]) for 27.327068618s.

python :

([1.100000000045252, 2.200000000090504, 3.3000000001880174], [1.1, 2.2, 3.3], [1.1, 2.2, 3.3]) for 1.81366938593s.

纯 Python 比 Numpy 快 15 倍!

最佳答案

您的 Fnumpy 较慢的原因是它包含 Fpython 未完成的额外步骤:在内存中创建 numpy 数组。如果您将 np_verticies=np.array(verticies) 行移到 Fnumpy 和计时部分之外,您的结果将大不相同:

>>NUMPY >>([1.1000000000452519, 2.2000000000905038, 3.3000000001880174], [1.1000000000000001, 2.2000000000000002, 3.2999999999999998], [1.1000000000000001, 2.2000000000000002, 3.2999999999999998]) for 0.500802s.
>>PYTHON>>([1.100000000045252, 2.200000000090504, 3.3000000001880174], [1.1, 2.2, 3.3], [1.1, 2.2, 3.3]) for 2.182239s.

您还可以通过在创建时向 numpy 提供数据类型提示来显着加快分配步骤。如果你告诉 Numpy 你有一个 float 数组,那么即使你将 np.array() 调用留在计时循环中,它也会击败纯 python 版本。

如果我将 np_vertices=np.array(vertices) 更改为 np_vertices=np.array(vertices, dtype=np.float_)将其保留在FnumpyFnumpy 版本将击败 Fpython,尽管它必须做更多的工作:

>>NUMPY >>([1.1000000000452519, 2.2000000000905038, 3.3000000001880174], [1.1000000000000001, 2.2000000000000002, 3.2999999999999998], [1.1000000000000001, 2.2000000000000002, 3.2999999999999998]) for 1.586066s.
>>PYTHON>>([1.100000000045252, 2.200000000090504, 3.3000000001880174], [1.1, 2.2, 3.3], [1.1, 2.2, 3.3]) for 2.196787s.

关于python - 纯 Python 比 Numpy 更快?我可以使这个 numpy 代码更快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15026519/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com