Python,如何优化这段代码

标签 python performance numpy cython

我试图优化下面的代码,但我不知道如何提高计算速度。我试过 Cthon,但性能就像在 python 中一样。

是否可以在不重写 C/C++ 中的所有内容的情况下提高性能?

感谢您的帮助

import numpy as np

heightSequence = 400
widthSequence = 400
nHeights = 80

DOF = np.zeros((heightSequence, widthSequence), dtype = np.float64)
contrast = np.float64(np.random.rand(heightSequence, widthSequence, nHeights))

initDOF = np.zeros([heightSequence, widthSequence], dtype = np.float64)
initContrast = np.zeros([heightSequence, widthSequence, nHeights], dtype = np.float64)
initHeight = np.float64(np.r_[0:nHeights:1.0])
initPixelContrast = np.array(([0 for ii in range(nHeights)]), dtype = np.float64)


# for each row
for row in range(heightSequence):
    # for each col
    for col in range(widthSequence):

        # initialize variables            
        height = initHeight # array ndim = 1
        c = initPixelContrast # array ndim = 1

        # for each height            
        for indexHeight in range(0, nHeights):
            # get contrast profile for current pixel
            tempC = contrast[:, :, indexHeight]
            c[indexHeight] = tempC[row, col]

        # save original contrast            
        # originalC = c
        # originalHeight = height                

        # remove profile before maximum and after minumum contrast
        idxMaxContrast = np.argmax(c)
        c = c[idxMaxContrast:]
        height = height[idxMaxContrast:]

        idxMinContrast = np.argmin(c) + 1
        c = c[0:idxMinContrast]
        height = height[0:idxMinContrast]              

        # remove some refraction
        if (len(c) <= 1) | (np.max(c) <= 0):
            DOF[row, col] = 0                  

        else:

            # linear fitting of profile contrast                                             
            P = np.polyfit(height, c, 1)
            m = P[0]
            q = P[1]

            # remove some refraction               
            if m >= 0:
                DOF[row, col] = 0

            else:
                DOF[row, col] = -q / m

    print 'row=%i/%i' %(row, heightSequence)

# set range of DOF
DOF[DOF < 0] = 0
DOF[DOF > nHeights] = 0

最佳答案

通过查看代码,您似乎可以完全摆脱两个外部循环,将代码转换为向量化 形式。然而,np.polyfit 调用必须被其他一些表达式替换,但是线性拟合的系数很容易找到,也是矢量化形式。最后一个 if-else 可以变成一个 np.where 调用。

关于Python,如何优化这段代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15134442/

相关文章:

performance - 用JMeter记录移动IOS/Android应用的HTTPS请求

python - 使用从 np.argsort() 返回的索引对 2D numpy 数组进行排序

python - Django 模型表单集 - 修改表单标签和默认值

python - 如何完全重置请求?

python - PyEphem 能否用于计算任何对象的设置和上升时间?

numpy - 一维数组的所有循环移位的二维数组

python-3.x - 将 numpy.ndarray 转换为小写

python - Python-Kivy:SoundLoader.load不起作用

iOS 推送通知 - 我可以在一分钟内从我的服务器发送多少?

C++代码性能