我正在使用python填充3d数组,每个数组元素代表一个像素。
我需要插入数组的值存储在一个非常大的.txt文件中(56百万行,格式如下 - x,y,z,r,g,b)
我现在:
对于5600万行,我需要大约160秒
如何使用python加快速度? (gpu可用)
array = np.zeros((height, width), dtype=np.float32)
with open(point_cloud_file) as pc_file:
while True:
line = pc_file.readline()
if not line:
break
nof_read_lines += 1
new_line = line.strip()
try:
x, y, z, _, _, _ = new_line.split(',')
except:
nof_skipped_lines += 1
continue
# insert to array
pixel_x = some calculation
pixel_y = some calculation
if 0 < pixel_x < width and 0 < pixel_y < height:
if array[int(pixel_y), int(pixel_x), 0] == 0:
array[int(pixel_y), int(pixel_x), :] = x, y, z
else:
nof_skipped_lines += 1 # pixel already filled with values
也许readlines()在这种情况下有用,这个例子一次读取所有行并将整个文件加载到内存中:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
但是您正在处理大型文本文件,因此您可以限制每个循环中的缓冲区使用情况
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
根据文档,file.readlines([sizehint]) sizehint是字节数