timings - Pastebin.com (original) (raw)

Tiran

Jun 22nd, 2012

767

0

Never

Not a member of Pastebin yet? Sign Up, it unlocks many cool features!

  1. # based on http://bpaste.net/show/32123/
  2. from hashlib import timingsafe_cmp
  3. from hmac import compare_digest
  4. import time
  5. def avg(lst):
  6. return sum(lst) / len(lst)
  7. def count_dev(lst):
  8. a = avg(lst)
  9. s = 0
  10. for k in lst:
  11. s += (a - k) * (a - k)
  12. return s**0.5 / len(lst)
  13. def f(compare, time):
  14. all = []
  15. all_diff = []
  16. x = b"gbgb"
  17. x += b"cdcd"
  18. y = b"abab"
  19. y += b"cdcd"
  20. for k in range(1000):
  21. t0 = time()
  22. for i in range(1000):
  23. compare(b"ababcdcd", x)
  24. dt = time() - t0
  25. all.append(dt)
  26. #print(dt)
  27. t0 = time()
  28. for i in range(1000):
  29. compare(b"ababcdcdcd", y)
  30. dt = time() - t0
  31. all_diff.append(dt)
  32. #print dt
  33. print(compare.__name__)
  34. print(avg(all), count_dev(all))
  35. print(avg(all_diff), count_dev(all_diff))
  36. if __name__ == "__main__":
  37. f(timingsafe_cmp, time.perf_counter)
  38. f(compare_digest, time.perf_counter)
  39. """Timings on my computer
  40. timingsafe_cmp
  41. 0.00018479363086953526 1.5809031608268674e-07
  42. 0.00018491724695195443 3.2265855903059935e-07
  43. compare_digest
  44. 0.0022960933020731316 4.3173793494042294e-06
  45. 0.0005554750110022724 3.691764413874176e-07
  46. """