首页 > 解决方案 > 如何优化将包含字节的多个文件读取到 NumPy 数组中

问题描述

我目前有大约 1000 个包含字节的文件。每个文件包含几千条消息,每条消息都有相同的数据类型。

我已经尝试了几种将其读入 numpy 数组的方法,但我很好奇我能以多快的速度获得它,因为目前所有尝试都非常慢。

就从文件中将其读入 python 而言,我发现预先创建一个具有正确大小的字节数组并使用file.readinto. 而不是file.read().

所以我留下了将字节放入 NumPy 数组的问题。下面是我的第一次迭代,87.5% 的时间花在 if-else 块中附加 numpy 数组。

count = 0
numpy_types = np.dtype([('col1','i8'),('col2','i8'),('col3','i8'),('col4','f4')])
for file in files:
    byte_array = bytearray(file.filelength)
    with open(file, 'rb') as f:
        f.readinto(byte_array)
        array = np.frombuffer(byte_array, numpy_types)
        if count == 0:
            numpy_array = array
        else:
            numpy_array = np.append(numpy_array, array)

如果有人想在家里尝试这个,我将重复上面的示例,并使用可以复制和粘贴的版本进行另一次尝试。


第一次尝试

将每个文件读入一个单独的 numpy 数组并将它们附加在一起

import numpy as np
import time
start = time.time()
byte_array = b''
bytes1 = b'\x00\xe8n\x14Z\x1d\xd8\x08\xff\xff\xff\xff\xff\xff\xff\xff\x00\xdd\x90\xa7\x16/\xd8\x08ff\xe0A'
# Create the byte array identical to what would be read in from each file
for i in range(1000):
        byte_array += bytes1



numpy_dtypes = np.dtype([('col1','i8'), ('col2', 'i8'), ('col3', 'i8'), ('col4', 'f4')])
total_time = 0
# Imitate loop of reading in multiple files
for i in range(1000):
    array = np.frombuffer(byte_array, numpy_dtypes)
    start2 = time.time()
    if i == 0:
        numpy_array = array
    else:
        numpy_array = np.append(numpy_array, array)
    total_time += (time.time() - start2)
print(f'took {total_time} to append numpy arrays together')
print(f'took {time.time()-start:.2f} seconds in total')

第二次尝试

我尝试将所有字节附加到单个字节数组,然后立即读入一个 numpy 数组

import numpy as np
import time
start = time.time()
byte_array = b''
bytes1 = b'\x00\xe8n\x14Z\x1d\xd8\x08\xff\xff\xff\xff\xff\xff\xff\xff\x00\xdd\x90\xa7\x16/\xd8\x08ff\xe0A'
# Create the byte array identical to what would be read in from each file
for i in range(1000):
        byte_array += bytes1


numpy_dtypes = np.dtype([('col1','i8'), ('col2', 'i8'), ('col3', 'i8'), ('col4', 'f4')])
# Imitate loop of reading in multiple files
total_bytes = b''
start2 = time.time()
for i in range(1000):
    total_bytes += byte_array
print(f'took {time.time()-start2:.2f} seconds to append bytes together')
numpy_array = np.frombuffer(total_bytes, numpy_dtypes)
print(f'took {time.time()-start:.2f} seconds')

为什么大部分处理时间来自将数据附加在一起?有没有更好的方法来解决这个问题,因为这似乎是瓶颈。无论是将所有数据附加在一起,还是从读取所有数据的初始方式开始。我也尝试过 struct.unpack 但这仍然很慢,据我所知,NumPy 在读取字节方面更快。

标签: pythonnumpyiobyte

解决方案


推荐阅读