【发布时间】:2013-07-17 21:17:54
【问题描述】:
这是参考Get MD5 hash of big files in Python和Hashlib in Windows and Linux
在回答这两个问题时,建议在函数 md5.update() 中使用更大的数据块来提高性能。
我所做的所有测试似乎都表明使用较小的块可以获得最佳性能。
考虑以下代码:
def test(factor):
filehash = hashlib.md5()
blk_size_to_read = filehash.block_size * (2**factor)
with open(largetestfile, 'rb') as f:
read_data = f.read(blk_size_to_read)
filehash.update(read_data)
filehash.digest()
if __name__ == '__main__':
for ctr in xrange(0, 12):
funcstr = "test({})".format(str(ctr))
timetaken = timeit.timeit(funcstr, setup="from __main__ import test", number = 5000)
print "Factor: {} Time: {}".format(str(ctr), str(timetaken))
我所做的所有测试都表明,使用factor 0 或 1(即 64 或 128 字节)时性能最佳。
为什么我看到的结果与引用的问题中的结果不同?
我尝试过大小从 700MB 到 1.2GB 的二进制和纯文本文件,并且在 Ubuntu 12.04 上使用 Python 2.7.3
次要问题:我是否按照应有的方式使用 timeit?
【问题讨论】: