是否有使用不同版本的SHA哈希的显著开销(hashlib模块)
题
在 hashlib
Python模块提供了以下的散列算法的构造:md5()
,sha1()
,sha224()
,sha256()
,sha384()
,和sha512()
。
假如我不希望使用MD5,有没有使用,比如说,SHA1代替SHA512大的差别?我想使用类似hashlib.shaXXX(hashString).hexdigest()
,但它只是缓存,我不知道我需要的512(最终)额外的开销......
这是否存在开销,如果是的话,有多大呢?
解决方案
为什么不基准呢?
>>> def sha1(s):
... return hashlib.sha1(s).hexdigest()
...
>>> def sha512(s):
... return hashlib.sha512(s).hexdigest()
...
>>> t1 = timeit.Timer("sha1('asdf' * 100)", "from __main__ import sha1")
>>> t512 = timeit.Timer("sha512('asdf' * 100)", "from __main__ import sha512")
>>> t1.timeit()
3.2463729381561279
>>> t512.timeit()
6.5079669952392578
所以,我的机器上,hash512
的两倍,sha1
慢。但随着 GregS 说,你为什么要使用安全散列缓存?尝试内建的散列算法应该是非常快和调谐:
>>> s = "asdf"
>>> hash(s)
-618826466
>>> s = "xxx"
>>> hash(s)
943435
>>> hash("xxx")
943435
或者更好的是,使用内置的Python字典。也许你可以告诉我们更多关于你打算什么缓存
编辑: 我在想,你正在努力实现这样的:
hash = hashlib.sha1(object_to_cache_as_string).hexdigest()
cache[hash] = object_to_cache
什么我被“使用内置的Python dictinoaries” refferring到的是,可以简化上述:
cache[object_to_cache_as_string] = object_to_cache
在这种方式,Python的照顾散列的,所以你不必!
关于你提到的具体问题,你可以参考 Python的哈希的类型的字典为了使字典可哈希。然后,所有你需要做缓存的对象是:
cache[object_to_cache] = object_to_cache
其他提示
也许是幼稚的测试...但它看起来像它取决于你有多少散列。 SHA512的2块比SHA256的4个块快?
>>> import timeit
>>> import hashlib
>>> for sha in [ x for x in dir(hashlib) if x.startswith('sha') ]:
... t = timeit.Timer("hashlib.%s(data).hexdigest()" % sha,"import hashlib; data=open('/dev/urandom','r').read(1024)")
... print sha + "\t" + repr(t.timeit(1000))
...
sha1 0.0084478855133056641
sha224 0.034898042678833008
sha256 0.034902095794677734
sha384 0.01980900764465332
sha512 0.019846916198730469
不隶属于 StackOverflow