timings - Pastebin.com (original) (raw)
Jun 22nd, 2012
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
- # based on http://bpaste.net/show/32123/
- from hashlib import timingsafe_cmp
- from hmac import compare_digest
- import time
- def avg(lst):
- return sum(lst) / len(lst)
- def count_dev(lst):
- a = avg(lst)
- s = 0
- for k in lst:
- s += (a - k) * (a - k)
- return s**0.5 / len(lst)
- def f(compare, time):
- all = []
- all_diff = []
- x = b"gbgb"
- x += b"cdcd"
- y = b"abab"
- y += b"cdcd"
- for k in range(1000):
- t0 = time()
- for i in range(1000):
- compare(b"ababcdcd", x)
- dt = time() - t0
- all.append(dt)
- #print(dt)
- t0 = time()
- for i in range(1000):
- compare(b"ababcdcdcd", y)
- dt = time() - t0
- all_diff.append(dt)
- #print dt
- print(compare.__name__)
- print(avg(all), count_dev(all))
- print(avg(all_diff), count_dev(all_diff))
- if __name__ == "__main__":
- f(timingsafe_cmp, time.perf_counter)
- f(compare_digest, time.perf_counter)
- """Timings on my computer
- timingsafe_cmp
- 0.00018479363086953526 1.5809031608268674e-07
- 0.00018491724695195443 3.2265855903059935e-07
- compare_digest
- 0.0022960933020731316 4.3173793494042294e-06
- 0.0005554750110022724 3.691764413874176e-07
- """