Advertisement
Guest User

Untitled

a guest
Apr 24th, 2014
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. # dict comprehension
  2. new_d = {key: value for key, value in d.iteritems() if key >= guard_condition }
  3.  
  4. # resize while iterating
  5. for key in d:
  6. if key < guard_condition:
  7. del d[key]
  8.  
  9. In [140]: d = {item: item for item in xrange(10000)};
  10.  
  11. In [142]: guard_condition = 9000;
  12.  
  13. In [144]: %timeit new_d = {key: value for key, value in d.iteritems() if key >=
  14. 100 loops, best of 3: 2.54 ms per loop
  15.  
  16. In [140]: d = {item: item for item in xrange(10000)};
  17.  
  18. In [149]: def del_iter(d, guard_condition):
  19. .....: for key in d.keys():
  20. .....: if key < guard_condition:
  21. .....: del d[key]
  22. .....:
  23.  
  24. In [150]: %timeit del_iter(d, guard_condition)
  25. 1000 loops, best of 3: 232 us per loop
  26.  
  27. import cProfile, pstats, StringIO
  28. pr = cProfile.Profile()
  29. pr.enable()
  30.  
  31. guard_condition = int(raw_input("Enter guard_condition: "))
  32.  
  33. d = {item: item for item in xrange(10000000)};
  34.  
  35. new_d = {key: value for key, value in d.iteritems() if key >= guard_condition }
  36.  
  37. def del_iter(d, guard_condition):
  38. for key in d.keys():
  39. if key < guard_condition:
  40. del d[key]
  41.  
  42. del_iter(d, guard_condition)
  43.  
  44. pr.disable()
  45. s = StringIO.StringIO()
  46. sortby = 'cumulative'
  47. ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
  48. ps.print_stats()
  49. print s.getvalue()
  50.  
  51. ncalls tottime percall cumtime percall filename:lineno(function)
  52. 1 2.794 2.794 2.794 2.794 {raw_input}
  53. 1 1.263 1.263 1.263 1.263 dictDel1.py:7(<dictcomp>)
  54. 1 1.030 1.030 1.030 1.030 dictDel1.py:9(<dictcomp>) <-- dict comprehension
  55. 1 0.892 0.892 0.976 0.976 dictDel1.py:11(del_iter) <-- resize while iterating
  56. 1 0.085 0.085 0.085 0.085 {method 'keys' of 'dict' objects}
  57. 1 0.000 0.000 0.000 0.000 {method 'iteritems' of 'dict' objects}
  58. 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
  59.  
  60. ncalls tottime percall cumtime percall filename:lineno(function)
  61. 1 3.316 3.316 3.316 3.316 {raw_input}
  62. 1 1.247 1.247 1.247 1.247 dictDel1.py:7(<dictcomp>)
  63. 1 0.937 0.937 1.052 1.052 dictDel1.py:11(del_iter) <-- resize while iterating
  64. 1 0.787 0.787 0.787 0.787 dictDel1.py:9(<dictcomp>) <-- dict comprehension
  65. 1 0.115 0.115 0.115 0.115 {method 'keys' of 'dict' objects}
  66. 1 0.000 0.000 0.000 0.000 {method 'iteritems' of 'dict' objects}
  67. 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement