Advertisement
Tiran

timings

Jun 22nd, 2012
691
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. # based on http://bpaste.net/show/32123/
  2.  
  3. from hashlib import timingsafe_cmp
  4. from hmac import compare_digest
  5. import time
  6.  
  7. def avg(lst):
  8.     return sum(lst) / len(lst)
  9.  
  10. def count_dev(lst):
  11.     a = avg(lst)
  12.     s = 0
  13.     for k in lst:
  14.         s += (a - k) * (a - k)
  15.     return s**0.5 / len(lst)
  16.  
  17. def f(compare, time):
  18.     all = []
  19.     all_diff = []
  20.     x = b"gbgb"
  21.     x += b"cdcd"
  22.     y = b"abab"
  23.     y += b"cdcd"
  24.     for k in range(1000):
  25.         t0 = time()
  26.         for i in range(1000):
  27.             compare(b"ababcdcd", x)
  28.         dt = time() - t0
  29.         all.append(dt)
  30.         #print(dt)
  31.         t0 = time()
  32.         for i in range(1000):
  33.             compare(b"ababcdcdcd", y)
  34.         dt = time() - t0
  35.         all_diff.append(dt)
  36.         #print dt
  37.     print(compare.__name__)
  38.     print(avg(all), count_dev(all))
  39.     print(avg(all_diff), count_dev(all_diff))
  40.  
  41. if __name__ == "__main__":
  42.     f(timingsafe_cmp, time.perf_counter)
  43.     f(compare_digest, time.perf_counter)
  44.  
  45. """Timings on my computer
  46.  
  47. timingsafe_cmp
  48. 0.00018479363086953526 1.5809031608268674e-07
  49. 0.00018491724695195443 3.2265855903059935e-07
  50. compare_digest
  51. 0.0022960933020731316 4.3173793494042294e-06
  52. 0.0005554750110022724 3.691764413874176e-07
  53. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement