简体   繁体   English

使用 Numpy Python 提高迭代 function 的性能

[英]Increasing the performance of an iterating function with Numpy Python

Is there a way I could run the function below on pure numpy, so I am trying to get rid of the for loop.有没有办法可以在纯 numpy 上运行下面的 function,所以我试图摆脱 for 循环。 I am trying to decrease the runtime of my code.我正在尝试减少代码的运行时间。 Number_array is added on with each each element of Values and summed. Number_arrayValues的每个元素相加并求和。 The sum is appended onto the Appending_list after each iteration.每次迭代后,总和将附加到Appending_list中。 The Number_array makes 10000000 integers between 0 to 100. Number_array在 0 到 100 之间生成 10000000 个整数。

Code:代码:

import numpy as np
from numpy import random
Appending_list = []
Values = random.randint(100, size=(100000))
Number_array = random.randint(100, size=(1000))
for n in range(len(Values)):
    result = np.sum([Number_array + Values[n]])
    Appending_list.append(result)

Performance:表现:

在此处输入图像描述

Your code for comparison:您的比较代码:

Appending_list = []
for n in range(len(Values)):
    result = np.sum([Number_array + Values[n]])
    Appending_list.append(result)

Writing the sum a different way:用不同的方式写总和:

Appending_list = []
for n in range(len(Values)):
    result = np.sum(Number_array) + Values[n] * len(Number_array)
    Appending_list.append(result)

And that is easy to vectorize:这很容易矢量化:

Appending_list = np.sum(Number_array) + Values * len(Number_array)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM