Python的SequenceMatcher开销 - 100%的CPU使用率和速度很慢处理
题
我使用difflib在两个目录(版本从连续几年)来比较文件。 首先,我使用filecmp发现已更改的文件,然后反复使用difflib.SequenceMatcher对它们进行比较,并生成一个HTML差异作为解释的此处。
但是,我发现程序花费的时间太长运行和Python是利用100%的CPU。上时间分析,我发现,在 seqm.get_opcodes()强>呼叫被采取的所有时间。
任何了解,将不胜感激。 谢谢!
代码:
#changed_set contains the files to be compared
for i in changed_set:
oldLines = open(old_dir +"/" + i).read()
newLines = open(new_dir +"/" + i).read()
seqm = difflib.SequenceMatcher(lambda(x): x in string.whitespace, oldLines, newLines)
opcodes = seqm.get_opcodes() #XXX: Lots of time spent in this !
produceDiffs(seqm, opcodes)
del seqm
解决方案
我的答案是不同的解决问题的方法干脆:尝试使用版本控制系统如Git调查目录如何改变了多年来
。请一个仓库出来的第一个目录中,然后替换为明年的目录内容,并承诺,作为一个改变。 (或移动.git目录到明年的目录,以节省拷贝/删除)。重复。
然后运行gitk,你就可以看到树的任意两个版本之间发生了什么变化。要么只是一个二进制文件改变,或者与文本文件一个diff。
其他提示
您也可以尝试 diff-match-patch
库,以我的经验也可以是快10倍。
编辑:例我的其他此处答案
from diff_match_patch import diff_match_patch
def compute_similarity_and_diff(text1, text2):
dmp = diff_match_patch()
dmp.Diff_Timeout = 0.0
diff = dmp.diff_main(text1, text2, False)
# similarity
common_text = sum([len(txt) for op, txt in diff if op == 0])
text_length = max(len(text1), len(text2))
sim = common_text / text_length
return sim, diff
不隶属于 StackOverflow