fork download
  1. import timeit
  2.  
  3. # List creation needs to be inside the timing loop for a fair timing
  4. # of the mutative option, so we time the list creation and subtract the
  5. # time from the other timings.
  6.  
  7. list_creation = r'''
  8. a = [0, 1] * 7
  9. '''
  10.  
  11. using_loop = list_creation + r'''
  12. for n, i in enumerate(a):
  13. if i == 1:
  14. a[n] = 10
  15. '''
  16.  
  17. using_comprehension = list_creation + r'''
  18. b = [10 if x==1 else x for x in a]
  19. '''
  20.  
  21. list_creation_time = timeit.timeit(list_creation, number=1000000)
  22. loop_time = timeit.timeit(using_loop, number=1000000) - list_creation_time
  23. comprehension_time = timeit.timeit(using_comprehension, number=1000000) - list_creation_time
  24.  
  25. print("Loop time: ", loop_time)
  26. print("Comprehension time:", comprehension_time)
Success #stdin #stdout 1.95s 9792KB
stdin
Standard input is empty
stdout
Loop time:          0.8592739272862673
Comprehension time: 0.7442726250737906