如何使用第3方安装的模块替换Python Build-in方法?

时间:2019-07-11 18:08:17

标签: python pbkdf2

我正在优化我的代码,并以快40%的Fast PBKDF2实现python-fastpbkdf2替换了Python内置的hashlib.pbkdf2_hmac。

但是,使用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)


1 个答案:

答案 0 :(得分:2)

您确实使用了快速PBKDF2模块,如cProfile输出所示。

我猜python-fastpbkdf2所做的任何性能测量都与旧版本的Python,OpenSSL或两者进行比较,而新版本的速度有所提高(而Fast PBKDF2却没有看到超过三个版本的更新)年份)。碰巧的是,它看起来像是截至2016年(Fast PBKDF2看到其最新更新的一年),而不是Python的本地(慢速)版本。甚至在此之前,Python added a fast path when linked against OpenSSL 1.1.0 or higher that uses OpenSSL's optimized PKCS5_PBKDF2_HMAC;如果在发布该改进之前运行python-fastpbkdf2基准测试,则性能会差很多。

基本上,即使过去曾经是真实的,也不要认为宣称速度提高40%的说法是真实的(并且也不能保证它们在过去也是真实的)。

编译器和/或软件包回购维护者还可能构建了更好的OpenSSL版本; Fast PBKDF2所声称的至少一项好处是,他明确地内联了许多操作,但是使用PGO + LTO正确编译的OpenSSL版本无论如何都会自动内联适当的操作(并且如果{{ 1}}未使用PGO + LTO正确构建,因此可能会丢失。在与进行类似代码改进的OpenSSL之间,差距很容易缩小。