1# It's intended that this script be run by hand. It runs speed tests on 2# hashlib functions; it does not test for correctness. 3 4import sys 5import time 6import hashlib 7 8 9def creatorFunc(): 10 raise RuntimeError("eek, creatorFunc not overridden") 11 12def test_scaled_msg(scale, name): 13 iterations = 106201//scale * 20 14 longStr = b'Z'*scale 15 16 localCF = creatorFunc 17 start = time.perf_counter() 18 for f in range(iterations): 19 x = localCF(longStr).digest() 20 end = time.perf_counter() 21 22 print(('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name) 23 24def test_create(): 25 start = time.perf_counter() 26 for f in range(20000): 27 d = creatorFunc() 28 end = time.perf_counter() 29 30 print(('%2.2f' % (end-start)), "seconds", '[20000 creations]') 31 32def test_zero(): 33 start = time.perf_counter() 34 for f in range(20000): 35 x = creatorFunc().digest() 36 end = time.perf_counter() 37 38 print(('%2.2f' % (end-start)), "seconds", '[20000 "" digests]') 39 40 41 42hName = sys.argv[1] 43 44# 45# setup our creatorFunc to test the requested hash 46# 47if hName in ('_md5', '_sha'): 48 exec('import '+hName) 49 exec('creatorFunc = '+hName+'.new') 50 print("testing speed of old", hName, "legacy interface") 51elif hName == '_hashlib' and len(sys.argv) > 3: 52 import _hashlib 53 exec('creatorFunc = _hashlib.%s' % sys.argv[2]) 54 print("testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2])) 55elif hName == '_hashlib' and len(sys.argv) == 3: 56 import _hashlib 57 exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2]) 58 print("testing speed of _hashlib.new(%r)" % sys.argv[2]) 59elif hasattr(hashlib, hName) and hasattr(getattr(hashlib, hName), '__call__'): 60 creatorFunc = getattr(hashlib, hName) 61 print("testing speed of hashlib."+hName, getattr(hashlib, hName)) 62else: 63 exec("creatorFunc = lambda x=hashlib.new : x(%r)" % hName) 64 print("testing speed of hashlib.new(%r)" % hName) 65 66try: 67 test_create() 68except ValueError: 69 print() 70 print("pass argument(s) naming the hash to run a speed test on:") 71 print(" '_md5' and '_sha' test the legacy builtin md5 and sha") 72 print(" '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib") 73 print(" '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)") 74 print(" 'hName' tests the hashlib.hName() implementation if it exists") 75 print(" otherwise it uses hashlib.new(hName).") 76 print() 77 raise 78 79test_zero() 80test_scaled_msg(scale=106201, name='[huge data]') 81test_scaled_msg(scale=10620, name='[large data]') 82test_scaled_msg(scale=1062, name='[medium data]') 83test_scaled_msg(scale=424, name='[4*small data]') 84test_scaled_msg(scale=336, name='[3*small data]') 85test_scaled_msg(scale=212, name='[2*small data]') 86test_scaled_msg(scale=106, name='[small data]') 87test_scaled_msg(scale=creatorFunc().digest_size, name='[digest_size data]') 88test_scaled_msg(scale=10, name='[tiny data]') 89