Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # dict comprehension
- new_d = {key: value for key, value in d.iteritems() if key >= guard_condition }
- # resize while iterating
- for key in d:
- if key < guard_condition:
- del d[key]
- In [140]: d = {item: item for item in xrange(10000)};
- In [142]: guard_condition = 9000;
- In [144]: %timeit new_d = {key: value for key, value in d.iteritems() if key >=
- 100 loops, best of 3: 2.54 ms per loop
- In [140]: d = {item: item for item in xrange(10000)};
- In [149]: def del_iter(d, guard_condition):
- .....: for key in d.keys():
- .....: if key < guard_condition:
- .....: del d[key]
- .....:
- In [150]: %timeit del_iter(d, guard_condition)
- 1000 loops, best of 3: 232 us per loop
- import cProfile, pstats, StringIO
- pr = cProfile.Profile()
- pr.enable()
- guard_condition = int(raw_input("Enter guard_condition: "))
- d = {item: item for item in xrange(10000000)};
- new_d = {key: value for key, value in d.iteritems() if key >= guard_condition }
- def del_iter(d, guard_condition):
- for key in d.keys():
- if key < guard_condition:
- del d[key]
- del_iter(d, guard_condition)
- pr.disable()
- s = StringIO.StringIO()
- sortby = 'cumulative'
- ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
- ps.print_stats()
- print s.getvalue()
- ncalls tottime percall cumtime percall filename:lineno(function)
- 1 2.794 2.794 2.794 2.794 {raw_input}
- 1 1.263 1.263 1.263 1.263 dictDel1.py:7(<dictcomp>)
- 1 1.030 1.030 1.030 1.030 dictDel1.py:9(<dictcomp>) <-- dict comprehension
- 1 0.892 0.892 0.976 0.976 dictDel1.py:11(del_iter) <-- resize while iterating
- 1 0.085 0.085 0.085 0.085 {method 'keys' of 'dict' objects}
- 1 0.000 0.000 0.000 0.000 {method 'iteritems' of 'dict' objects}
- 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
- ncalls tottime percall cumtime percall filename:lineno(function)
- 1 3.316 3.316 3.316 3.316 {raw_input}
- 1 1.247 1.247 1.247 1.247 dictDel1.py:7(<dictcomp>)
- 1 0.937 0.937 1.052 1.052 dictDel1.py:11(del_iter) <-- resize while iterating
- 1 0.787 0.787 0.787 0.787 dictDel1.py:9(<dictcomp>) <-- dict comprehension
- 1 0.115 0.115 0.115 0.115 {method 'keys' of 'dict' objects}
- 1 0.000 0.000 0.000 0.000 {method 'iteritems' of 'dict' objects}
- 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