fork download
  1. import timeit
  2.  
  3. setup = """
  4. class X:
  5. def __init__(self):
  6. self.n = 2
  7. def f0(self):
  8. return 0
  9. def f1(self):
  10. return 1
  11. def f2(self):
  12. return 2
  13. def f3(self):
  14. return 3
  15. x = X()
  16. d = {0: x.f0, 1: x.f1, 2: x.f2, 3: x.f3}
  17. """
  18. # If-statement 1
  19. code1 = """
  20. if x.n == 0:
  21. x.n = x.f0()
  22. elif x.n == 1:
  23. x.n = x.f1()
  24. elif x.n == 2:
  25. x.n = x.f2()
  26. elif x.n == 3:
  27. x.n = x.f3()
  28. """
  29. # If-statement 2
  30. code2 = """
  31. n = x.n
  32. if n == 0:
  33. x.n = x.f0()
  34. elif n == 1:
  35. x.n = x.f1()
  36. elif n == 2:
  37. x.n = x.f2()
  38. elif n == 3:
  39. x.n = x.f3()
  40. """
  41. # Dictionary 1
  42. code3 = """
  43. try:
  44. x.n = d[x.n]()
  45. except KeyError:
  46. pass
  47. """
  48. # Dictionary 2
  49. code4 = """
  50. x.n = d.get(x.n, lambda: x.n)()
  51. """
  52.  
  53. print timeit.Timer(code1, setup).timeit(), "If-statement 1"
  54. print timeit.Timer(code2, setup).timeit(), "If-statement 2"
  55. print timeit.Timer(code3, setup).timeit(), "Dictionary 1"
  56. print timeit.Timer(code4, setup).timeit(), "Dictionary 2"
  57.  
Success #stdin #stdout 3.57s 6740KB
stdin
Standard input is empty
stdout
1.01429390907 If-statement 1
0.895260095596 If-statement 2
0.578783988953 Dictionary 1
1.08309197426 Dictionary 2