加速处理以空格分隔数据段的Python函数
我需要处理一些文件,这些文件里的数据段是用空格分开的,比如:
93.18 15.21 36.69 33.85 16.41 16.81 29.17
21.69 23.71 26.38 63.70 66.69 0.89 39.91
86.55 56.34 57.80 98.38 0.24 17.19 75.46
[...]
1.30 73.02 56.79 39.28 96.39 18.77 55.03
99.95 28.88 90.90 26.70 62.37 86.58 65.05
25.16 32.61 17.47 4.23 34.82 26.63 57.24
36.72 83.30 97.29 73.31 31.79 80.03 25.71
[...]
2.74 75.92 40.19 54.57 87.41 75.59 22.79
.
.
.
为此,我正在使用以下这个函数。每次调用这个函数时,我都能得到需要的数据,但我想让代码运行得更快。
有没有更有效的方法呢?
编辑:我会更新代码,加入一些改进的内容
原始代码:
def get_pos_nextvalues(pos_file, indices):
result = []
for line in pos_file:
line = line.strip()
if not line:
break
values = [float(value) for value in line.split()]
result.append([float(values[i]) for i in indices])
return np.array(result)
新代码:
def get_pos_nextvalues(pos_file, indices):
result = ''
for line in pos_file:
if len(line) > 1:
s = line.split()
result += ' '.join([s [i] for i in indices])
else:
break
else:
return np.array([])
result = np.fromstring(result, dtype=float, sep=' ')
result = result.reshape(result.size/len(indices), len(indices))
return result
.
pos_file = open(filename, 'r', buffering=1024*10)
[...]
while(some_condition):
vs = get_pos_nextvalues(pos_file, (4,5,6))
[...]
加速效果 = 2.36
6 个回答
1
试着增加读取缓冲区的大小,因为输入输出可能是你代码的瓶颈。
open('file.txt', 'r', 1024 * 10)
另外,如果数据是连续的,你可以尝试跳过逐行处理的代码,一次性处理多行数据。
1
不要用:
if len(line) <= 1: # only '\n' in «empty» lines
break
values = line.split()
试试这个:
values = line.split()
if not values: # line is wholly whitespace, end of segment
break
2
首先,不要把浮点数转换成浮点数,这一步很重要。不过,我建议你先分析一下你的代码,找出性能瓶颈,然后再去优化那些慢的部分。
我知道你已经修改了原来的代码,但
values = [value for value in line.split()]
这样也不是个好主意。如果你是这个意思,就直接写 values = line.split()
吧。
既然你在用NumPy,我建议你看看一些文档中展示的文件读取方法。