【发布时间】:2011-10-04 10:31:02
【问题描述】:
我需要比较大块数据的相等性,并且我需要每秒比较很多对,快。保证每个对象的长度相同,有可能并且很可能仅在未知位置存在细微差异。
下面的时序表明,如果在数据开头附近有差异,则使用 == 运算符非常快,如果差异位于接近末尾,则速度明显较慢。
>>> import os
>>> s = os.urandom(1600*1200 - 1)
>>> Aimg = b"A" + s
>>> Bimg = b"B" + s
>>> img1 = s + b"1"
>>> img2 = s + b"2"
>>> %timeit Aimg == Bimg
61.8 ns ± 0.484 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> %timeit img1 == img2
159 µs ± 2.83 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
在我的用例中,差异可能位于字节的中间或末尾(上下文:它是未压缩的图像数据)。我寻找一种使用哈希或校验和来加快速度的方法。使用 md5 速度较慢,但 Python 的内置 hash 确实加快了速度。
>>> %timeit img1 == img2
160 µs ± 5.96 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit hash(img1) == hash(img2) and img1 == img2
236 ns ± 5.91 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
我对此哈希的技术细节感兴趣,它是否足够像 hash(a) == hash(b) 然后 a == b 时的哈希很有可能?如果哈希冲突相当罕见,则可以接受误报,其目的是在平均情况下加快比较速度。
【问题讨论】:
-
hash函数依赖于架构
标签: python hash hash-collision