Advertisement
Guest User

dict vs defaultdict

a guest
May 9th, 2014
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. from collections import defaultdict as dd
  4. import time
  5.  
  6. SIZE = 1000
  7. CYCLES = 10000
  8.  
  9. def ddTest():
  10.     d = dd(lambda:'NA')
  11.     for x in xrange(SIZE):
  12.         d[x]
  13.     return d
  14.  
  15. def dTest():
  16.     d = {}
  17.     for x in xrange(SIZE):
  18.         d[x] = d.get(x, 'NA')
  19.     return d
  20.  
  21. def ddFreq():
  22.     freq = dd(int)
  23.     for x in xrange(SIZE):
  24.         freq[x%7] += 1
  25.     return freq
  26.  
  27. def dFreq1():
  28.     freq = {}
  29.     for x in xrange(SIZE):
  30.         m = x%7
  31.         freq[m] = freq.get(m, 0) + 1
  32.     return freq
  33.  
  34. def dFreq2():
  35.     freq = {}
  36.     for x in xrange(SIZE):
  37.         freq[x%7] = freq.get(x%7, 0) + 1
  38.     return freq
  39.  
  40. def dFreq3():
  41.     freq = {}
  42.     for x in xrange(SIZE):
  43.         m = x%7
  44.         if m in freq:
  45.             freq[m] += 1
  46.         else:
  47.             freq[m] = 1
  48.     return freq
  49.  
  50. def tryList():
  51.     freq = [0 for x in xrange(7)]
  52.     for x in xrange(SIZE):
  53.         freq[x%7] += 1
  54.     return freq
  55.  
  56. def test(f):
  57.     tStart = time.time()
  58.     for x in xrange(CYCLES):
  59.         result = f()
  60.     tElapsed = time.time() - tStart
  61.     print ("%8s took %.3f seconds and returned a %s with %s items" %
  62.                 (f.__name__, tElapsed, type(result), len(result)))
  63.     return result
  64.  
  65. if __name__ == '__main__':
  66.     test(ddTest)
  67.     test(dTest)
  68.     test(ddFreq)
  69.     test(dFreq1)
  70.     test(dFreq2)
  71.     test(dFreq3)
  72.     test(tryList)
  73. -------------------------------------------------
  74. Output using Python 2.7.2 on seven-year-old MBP:
  75.  
  76.   ddTest took 5.866 seconds and returned a <type 'collections.defaultdict'> with 1000 items
  77.    dTest took 3.616 seconds and returned a <type 'dict'> with 1000 items
  78.   ddFreq took 3.087 seconds and returned a <type 'collections.defaultdict'> with 7 items
  79.   dFreq1 took 5.115 seconds and returned a <type 'dict'> with 7 items
  80.   dFreq2 took 5.446 seconds and returned a <type 'dict'> with 7 items
  81.   dFreq3 took 3.827 seconds and returned a <type 'dict'> with 7 items
  82.  tryList took 2.432 seconds and returned a <type 'list'> with 7 items
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement