Created
March 30, 2020 19:49
-
-
Save HacKanCuBa/7f93ccab4d6c8772904fd7141b56e1d2 to your computer and use it in GitHub Desktop.
Measure execution time of hashing functions from hashlib in Python3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Time hashlib hashing functions. | |
Useful to help decide which one to use if time is of the escence. I still recommend | |
blake2 or sha384. | |
Copyright © 2020 HacKan <@hackancuba> | |
This program is free software. It comes without any warranty, to | |
the extent permitted by applicable law. You can redistribute it | |
and/or modify it under the terms of the Do What The Fuck You Want | |
To Public License, Version 2, as published by Sam Hocevar. See | |
http://www.wtfpl.net/ for more details. | |
""" | |
import hashlib | |
import random | |
import string | |
from statistics import mean | |
print('Timing hashing functions from hashlib, this can take a while (maybe more', | |
'than 5 minutes!)...') | |
hashing_functions = hashlib.algorithms_available | |
data = ''.join(random.choice(string.ascii_letters) for x in range(1024*1024)).encode() | |
times = {} | |
for hashing_function in hashing_functions: | |
if not hasattr(hashlib, hashing_function): | |
print(hashing_function, 'not available') | |
continue | |
time = timeit.repeat(f'hashlib.{hashing_function}(data)', number=1000, | |
setup=f'import hashlib; data={data}') | |
times[hashing_function] = mean(time) | |
print(hashing_function, time) | |
print() | |
print('From fastest to slowest:') | |
times_sorted = sorted(times.items(), key = lambda item: item[1]) | |
baseline_time = None | |
for hashing_function, time in times_sorted: | |
if not baseline_time: | |
baseline_time = time | |
percentage = 100 | |
else: | |
percentage = time * 100 / baseline_time | |
padding_ammount = 20 - len(hashing_function) | |
padding = padding_ammount * ' ' | |
print(f'{hashing_function}{padding}{percentage:.2f}%') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment