fork(2) download
  1. from timeit import timeit
  2. from collections import defaultdict, Counter
  3. from random import shuffle
  4. from itertools import product
  5.  
  6. def f():
  7. d = {}
  8. for i, j in edges:
  9. if i not in d:
  10. d[i] = {j: 1}
  11. elif j in d[i]:
  12. d[i][j] += 1
  13. else:
  14. d[i][j] = 1
  15.  
  16. def g():
  17. d = defaultdict(lambda: defaultdict(int))
  18. for i, j in edges:
  19. d[i][j] += 1
  20.  
  21. def h():
  22. d = defaultdict(Counter)
  23. for i, j in edges:
  24. d[i][j] += 1
  25.  
  26. edges = list(product(range(300), repeat=2)) * 10
  27. shuffle(edges)
  28. for _ in range(2):
  29. print 'dict[dict[int]] ', timeit(f, number=1)
  30. print 'defdict[defdict[int]', timeit(g, number=1)
  31. print 'defdict[Counter] ', timeit(h, number=1)
  32. print
Success #stdin #stdout 1.82s 27396KB
stdin
Standard input is empty
stdout
dict[dict[int]]      0.217535972595
defdict[defdict[int] 0.155460834503
defdict[Counter]     0.328627109528

dict[dict[int]]      0.210070133209
defdict[defdict[int] 0.14684009552
defdict[Counter]     0.341432094574