我正在尝试从一个巨大的文件中构建一些int对。一个典型文件中的每个集合都包含大约几百万行以进行分析并从中建立一个集合。我创建了以下代码,但是用200万行制作的一组代码要花36个小时以上!!
输入文件(像这样的几百万行):以
开头*|NET 2 0.000295965PF ... //unwanted sections R2_42 2:1 2:2 3.43756e-05 $a=2.909040 $lvl=99 $llx=15.449 $lly=9.679 $urx=17.309 $ury=11.243 R2_43 2:2 2:3 0.805627 $l=0.180 $w=1.564 $lvl=71 $llx=16.199 $lly=9.679 $urx=16.379 $ury=11.243 $dir=0 R2_44 2:2 2:4 4.16241 $l=0.930 $w=1.564 $lvl=71 $llx=16.379 $lly=9.679 $urx=17.309 $ury=11.243 $dir=0 R2_45 2:3 2:5 0.568889 $a=0.360000 $lvl=96 $llx=15.899 $lly=10.185 $urx=16.499 $ury=10.785 R2_46 2:3 2:6 3.35678 $l=0.750 $w=1.564 $lvl=71 $llx=15.449 $lly=9.679 $urx=16.199 $ury=11.243 $dir=0 R2_47 2:5 2:7 0.0381267 $l=0.301 $w=0.600 $lvl=8 $llx=16.199 $lly=10.200 $urx=16.500 $ury=10.800 $dir=0 R2_48 2:5 2:8 0.0378733 $l=0.299 $w=0.600 $lvl=8 $llx=15.900 $lly=10.200 $urx=16.199 $ury=10.800 $dir=0 *|NET OUT 0.000895965PF ...etc
最后,我需要从上面构建一组整数对,其中整数是由文件的第2列和第3列组成的列表的索引。 [(2:1,2:2),(2:2,2:3),(2:2,2:4),(2:3,2:5),(2:3,2:6) ,(2:5,2:7),(2:5,2:8)]变为 [(0,1),(1,2,3,(1,3),(2,4),(2,5),(4,6),(4,7)]
我对此进行了编码:
if __name__ == '__main__':
with open('myspf') as infile, open('tmp','w') as outfile:
copy = False
allspf = []
for line in infile:
if line.startswith("*|NET 2"):
copy = True
elif line.strip() == "":
copy = False
elif copy:
#capture col2 and col3
if line.startswith("R"):
allspf.extend(re.findall(r'^R.*?\s(.*?)\s(.*?)\s', line))
final = f6(list(itertools.chain(*allspf))) //to get unique list
#build the finalpairs again by index: I've found this was the bottleneck
for x in allspf:
left,right = x
outfile.write("({},{}),".format(final.index(left),final.index(right)))
pair = []
f = open('tmp')
pair = list(ast.literal_eval(f.read()))
f.close()
fopen = open('hopespringseternal.txt','w')
fopen.write((json.dumps(construct_trees_by_TingYu(pair), indent=1)))
fopen.close()
def f6(seq):
# Not order preserving
myset = set(seq)
return list(myset)
瓶颈在“ fors in allspf中的x”循环中,在我为它设置了数百万个项目集之后,construct_trees_by_TingYu过程本身也用完了内存。这个人的程序需要一次全部完成:http://xahlee.info/python/python_construct_tree_from_edge.html
最终输出是从父级到子级的一棵树:
{ "3": { "1": { "0": {} } }, "5": { "2": { "1": { "0": {} } } }, "6": { "4": { "2": { "1": { "0": {} } } } }, "7": { "4": { "2": { "1": { "0": {} } } } } }
答案 0 :(得分:0)
Building a set is always O(n)。您需要遍历整个列表以将每个项目添加到您的集合中。
但是,您似乎甚至没有在上面的代码摘录中使用set操作。
如果内存不足,则可能要遍历庞大的集合,而不是等待整个集合创建之后再将其传递给Construct_trees_by_TingYu(我不知道这是什么)。另外,您可以创建一个generator to yield each item from the set,这将减少您的内存占用。我不知道“ construct_trees_by_TingYu”是否会处理传递给它的生成器。