fork download
  1.  
  2.  
  3. def setup():
  4. global a_list
  5. a_list = [" raz sada ra r era kldfa d dh dsfh fhds h aergl jlk "]*500
  6.  
  7. def slice_comprehension():
  8. global a_list
  9. a_list[:] = (s.strip() for s in a_list)
  10.  
  11. def noslice_comprehension():
  12. global a_list
  13. a_list = [s.strip() for s in a_list]
  14.  
  15. def slice_map():
  16. global a_list
  17. a_list[:] = map(str.strip, a_list)
  18.  
  19. def noslice_map():
  20. global a_list
  21. a_list = map(str.strip, a_list)
  22.  
  23. def iter_enumerate():
  24. global a_list
  25. for i,x in enumerate(a_list):
  26. a_list[i] = x.strip()
  27.  
  28. def iter_range():
  29. global a_list
  30. for i in range(len(a_list)):
  31. a_list[i] = a_list[i].strip()
  32.  
  33. def iter_manual():
  34. global a_list
  35. i=0
  36. for x in a_list:
  37. a_list[i] = x.strip()
  38. i+=1
  39.  
  40. import timeit
  41. n=1000
  42. funcs = slice_comprehension, noslice_comprehension, slice_map, noslice_map, iter_enumerate, iter_range, iter_manual
  43. values = [(f.func_name, timeit.timeit(f, number=n, setup=setup)) for f in funcs]
  44. for i in sorted(values, key=lambda x: x[1]):
  45. print "{:25}: {}".format(*i)
Success #stdin #stdout 0.9s 10864KB
stdin
Standard input is empty
stdout
noslice_map              : 0.0814900398254
slice_map                : 0.084676027298
noslice_comprehension    : 0.0927240848541
slice_comprehension      : 0.124806165695
iter_manual              : 0.133514881134
iter_enumerate           : 0.142778873444
iter_range               : 0.160353899002