【发布时间】:2019-07-11 18:08:17
【问题描述】:
我正在优化我的代码并将 Python 内置 hashlib.pbkdf2_hmac 替换为快 40% 的 Fast PBKDF2 实现 python-fastpbkdf2。
但是使用 cProfile 的结果似乎是一样的。
我已经(尝试)确保使用 Fast PBKDF2 模块而不是内置的 hashlib.pbkdf2_hmac 模块,但我似乎不明白为什么我没有看到 40% 的性能提升。
from fastpbkdf2 import pbkdf2_hmac
phrase_words = "clerk great coin mistake become"
passphrase = 'passphrase'
seed = pbkdf2_hmac('sha512', bytes(complete_phrase_words, encoding='utf-8'), bytes('mnemonic' + passphrase, encoding='utf-8'), 2048)
如何确保不使用内置方法?
cProfile 报告:
186811385 function calls (186811349 primitive calls) in 885.041 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
109344 710.505 0.006 710.505 0.006 {built-in method _fastpbkdf2.fastpbkdf2_hmac_sha512}
57919431 54.060 0.000 54.060 0.000 {built-in method builtins.format}
57918564 45.288 0.000 116.547 0.000 crypto_awesomer_fast_pbkdf2_test.py:75(<genexpr>)
3619696 20.854 0.000 137.401 0.000 {method 'join' of 'str' objects}
57919431 20.604 0.000 20.604 0.000 {method 'zfill' of 'str' objects}
1755108 14.666 0.000 877.752 0.001 crypto_awesomer_fast_pbkdf2_test.py:66(validate)
1755108 4.119 0.000 4.119 0.000 {method 'to_bytes' of 'int' objects}
1755108 3.949 0.000 3.949 0.000 {method 'digest' of '_hashlib.HASH' objects}
1 3.825 3.825 884.982 884.982 crypto_awesomer_fast_pbkdf2_test.py:33(nested_loops)
1755109 2.859 0.000 2.859 0.000 {built-in method _hashlib.openssl_sha256}
109344 1.937 0.000 714.213 0.007 crypto_awesomer_fast_pbkdf2_test.py:89(generate_seed)
109344 1.315 0.000 712.156 0.007 __init__.py:18(pbkdf2_hmac)
【问题讨论】:
-
您是否安装了 OpenSSL? Python 使用 OpenSSL 提供的快速实现(如果可用,而不是内置实现),也许这就是您看不到速度差异的原因。似乎 python-fastpbkdf2 多年来没有更新,我会对他们的基准测试持保留态度。
-
确实如此。如果没有 OpenSSL,Fast PBKDF2 模块给了我“致命错误:找不到‘openssl/sha.h’文件”,我通过使用“brew install openssl”和“brew link --force openssl”安装 OpenSSL 解决了这个问题。