fork download
  1. #!/usr/bin/env python
  2. import timeit
  3.  
  4. first_transformation = lambda x: x + 1
  5. second_transformation = lambda x: x + 1
  6. third_transformation = lambda x: x + 1
  7.  
  8. n = 1000
  9. my_list = list(range(1000))
  10.  
  11. def timeit_args(f, args, *timeit_args, **timeit_kwargs):
  12. def testf():
  13. f(*args)
  14. return timeit.timeit(testf, *timeit_args, **timeit_kwargs)
  15.  
  16. try:
  17. xrange
  18. except NameError:
  19. xrange = range # Python 3
  20.  
  21. def one_pass(my_list):
  22. for i in xrange(0, len(my_list)):
  23. my_list[i] = first_transformation(my_list[i])
  24. my_list[i] = second_transformation(my_list[i])
  25. my_list[i] = third_transformation(my_list[i])
  26. return my_list
  27.  
  28. print('one_pass: ' + str(timeit_args(one_pass, [my_list], number=n)))
  29.  
  30. def multi_pass(my_list):
  31. range_end = len(my_list)
  32. for i in xrange(0, range_end):
  33. my_list[i] = first_transformation(my_list[i])
  34.  
  35. for i in xrange(0, range_end):
  36. my_list[i] = second_transformation(my_list[i])
  37.  
  38. for i in xrange(0, range_end):
  39. my_list[i] = third_transformation(my_list[i])
  40.  
  41. return my_list
  42.  
  43. print('multi_pass: ' + str(timeit_args(multi_pass, [my_list], number=n)))
  44.  
  45. def simple(my_list):
  46. return [third_transformation(second_transformation(first_transformation(e))) for e in my_list]
  47.  
  48. print('simple: ' + str(timeit_args(simple, [my_list], number=n)))
  49.  
Success #stdin #stdout 2.34s 10848KB
stdin
Standard input is empty
stdout
one_pass: 0.839533090591
multi_pass: 0.840938806534
simple: 0.569097995758