我正在执行下面的python代码。
我在一个文件夹(“文章”)上运行它,这个文件夹有几百个子文件夹,总共有240,226个文件。
我在计算行刑的时间。起初,时间是相当稳定的,但在100,000个文件之后变得非线性。现在,时间(我以10,000个文件间隔计时)可以在30,000左右(或更少)之后执行non_linear。
我打开了任务管理器,并将减速与python.exe的99%磁盘使用率关联起来。我已经做了gc-collect()。dels等,关闭了Windows索引。我重新启动了Windows,清空了垃圾桶(我有几百GB的空闲空间)。没有任何帮助,磁盘使用似乎变得更加不稳定。
很抱歉发了这么长的帖子--谢谢你的帮助
def get_filenames():
for (dirpath, dirnames, filenames) in os.walk("articles/"):
dirs.extend(dirnames)
for dir in dirs:
path = "articles" + "\\" + dir
nxml_files.extend(glob.glob(path + "/*.nxml"))
return nxml_files
def extract_text_from_files(nxml_files):
for nxml_file in nxml_files:
fast_parse(nxml_file)
def fast_parse(infile):
file = open(infile,"r")
filetext = file.read()
tag_breaks = filetext.split('><')
paragraphs = [tag_break.strip('p>').strip('</') for tag_break in tag_breaks if tag_break.startswith('p>')]
def run_files():
nxml_files = get_filenames()
extract_text_from_files(nxml_files)
if __name__ == "__main__":
run_files()发布于 2015-09-30 10:10:41
有些东西是可以优化的。
首先,你打开了文件,也关闭了它们。with open(...) as name:块很容易做到这一点。在Python2 file中,BTW是一个糟糕的变量名,它是内置函数的名称。
您可以通过执行字符串比较而不是glob来删除一个已读取的光盘。
最后但并非最不重要的一点是:os.walk巧妙地输出了结果,所以不要将它们缓冲到列表中,而是在一个循环中处理所有内容。这将节省大量内存。
这就是我能从代码中得到的建议。有关导致I/O的原因的更多详细信息,请使用性能分析。详情请参见https://docs.python.org/2/library/profile.html。
https://stackoverflow.com/questions/32854916
复制相似问题