python - 增长 numpy 数值数组的最快方法

标签 python performance numpy

要求:

  • 我需要从数据中增加一个任意大的数组。
  • 我可以猜测大小(大约 100-200),但不能保证每次都适合数组
  • 一旦它增长到最终大小,我需要对其执行数值计算,因此我希望最终得到一个二维 numpy 数组。
  • 速度至关重要。例如,对于 300 个文件中的一个,update() 方法被调用 4500 万次(大约需要 150s 左右),而 finalize() 方法被调用 500k 次(总共需要 106s)......总共需要 250s左右。

这是我的代码:

def __init__(self):
    self.data = []

def update(self, row):
    self.data.append(row)

def finalize(self):
    dx = np.array(self.data)

我尝试过的其他内容包括以下代码……但这要慢得多。

def class A:
    def __init__(self):
        self.data = np.array([])

    def update(self, row):
        np.append(self.data, row)

    def finalize(self):
        dx = np.reshape(self.data, size=(self.data.shape[0]/5, 5))

这是如何调用的示意图:

for i in range(500000):
    ax = A()
    for j in range(200):
         ax.update([1,2,3,4,5])
    ax.finalize()
    # some processing on ax

最佳答案

我尝试了一些不同的事情,有时间安排。

import numpy as np
  1. 你提到的慢的方法:(32.094秒)

    class A:
    
        def __init__(self):
            self.data = np.array([])
    
        def update(self, row):
            self.data = np.append(self.data, row)
    
        def finalize(self):
            return np.reshape(self.data, newshape=(self.data.shape[0]/5, 5))
    
  2. 常规ol Python列表:(0.308秒)

    class B:
    
        def __init__(self):
            self.data = []
    
        def update(self, row):
            for r in row:
                self.data.append(r)
    
        def finalize(self):
            return np.reshape(self.data, newshape=(len(self.data)/5, 5))
    
  3. 尝试在 numpy 中实现一个数组列表:(0.362 秒)

    class C:
    
        def __init__(self):
            self.data = np.zeros((100,))
            self.capacity = 100
            self.size = 0
    
        def update(self, row):
            for r in row:
                self.add(r)
    
        def add(self, x):
            if self.size == self.capacity:
                self.capacity *= 4
                newdata = np.zeros((self.capacity,))
                newdata[:self.size] = self.data
                self.data = newdata
    
            self.data[self.size] = x
            self.size += 1
    
        def finalize(self):
            data = self.data[:self.size]
            return np.reshape(data, newshape=(len(data)/5, 5))
    

这就是我的计时方式:

x = C()
for i in xrange(100000):
    x.update([i])

所以看起来普通的旧 Python 列表相当不错;)

关于python - 增长 numpy 数值数组的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7133885/

相关文章:

python - pymongo 返回与 MongoDB Shell 不同的数据

optimization - 特定例程的性能指标 : any best practices?

performance - elasticsearch的索引性能不佳

python - numpy.where 返回 int 而不是 float

python - 如何导入文件名包含 '-'字符的python模块

使用 Python.h undefined symbol 的 C++ 编译

python - 从文件中读取特定值并将它们存储在列表 python 中

c++ - 寻找用于 windows、c 或 c++ 的 TCP 套接字编程的最简单(也是最快)示例

python - Scipy inv(A) vs A.I

python - sin(y) 导致 "can' t 将表达式转换为 float"错误