Gia*_*ear 7 python sorting algorithm optimization performance
这是一个先前的问题,在哪里提高python中函数的时间性能我需要找到一种有效的方法来分割我的文本文件
我有以下文本文件(超过32 GB)未排序
....................
0 274 593869.99 6734999.96 121.83 1,
0 273 593869.51 6734999.92 121.57 1,
0 273 593869.15 6734999.89 121.57 1,
0 273 593868.79 6734999.86 121.65 1,
0 272 593868.44 6734999.84 121.65 1,
0 273 593869.00 6734999.94 124.21 1,
0 273 593868.68 6734999.92 124.32 1,
0 274 593868.39 6734999.90 124.44 1,
0 275 593866.94 6734999.71 121.37 1,
0 273 593868.73 6734999.99 127.28 1,
.............................
Run Code Online (Sandbox Code Playgroud)
第一列和第二列是网格中x,y,z点的位置的ID(例如:0-273).
def point_grid_id(x,y,minx,maxy,distx,disty):
"""give id (row,col)"""
col = int((x - minx)/distx)
row = int((maxy - y)/disty)
return (row, col)
Run Code Online (Sandbox Code Playgroud)
这(minx, maxx)是我的网格的大小的起源distx,disty.Id瓷砖的数量是
tiles_id = [j for j in np.ndindex(ny, nx)] #ny = number of row, nx= number of columns
from [(0,0),(0,1),(0,2),...,(ny-1,nx-1)]
n = len(tiles_id)
Run Code Online (Sandbox Code Playgroud)
我需要在n (= len(tiles_id))大量文件中切片~32 GB 文件.
我可以这样做而无需排序,但读取n次文件.出于这个原因,我希望找到一个有效的文件起始形式的拆分方法(0,0) (= tiles_id[0]).之后,我只能读取一次分割文件.
无论是使用Python还是命令行工具(sort),32GB文件几乎不可能进行排序.数据库似乎太强大,但可能会被使用.但是,如果您不愿意使用数据库,我建议您只使用tile id将源文件拆分为文件.
您读取一行,从tile标识中创建文件名并将该行附加到该文件.并继续,直到源文件完成.它不会太快,但至少与排序不同,它具有O(N)的复杂性.
当然,可以对文件进行单独排序并将它们连接起来.排序32GB文件的主要瓶颈应该是内存,而不是CPU.
在这里,我想:
def temp_file_name(l):
id0, id1 = l.split()[:2]
return "tile_%s_%s.tmp" % (id0, id1)
def split_file(name):
ofiles = {}
try:
with open(name) as f:
for l in f:
if l:
fn = temp_file_name(l)
if fn not in ofiles:
ofiles[fn] = open(fn, 'w')
ofiles[fn].write(l)
finally:
for of in ofiles.itervalues():
of.close()
split_file('srcdata1.txt')
Run Code Online (Sandbox Code Playgroud)
但是如果有很多瓷砖,你可以打开多个文件,你可以这样做:
def split_file(name):
with open(name) as f:
for l in f:
if l:
fn = temp_file_name(l)
with open(fn, 'a') as of:
of.write(l)
Run Code Online (Sandbox Code Playgroud)
最完美主义的方法是在达到打开文件编号的限制后关闭一些文件并将其从字典中删除.