fork download
  1. import timeit
  2. from collections import defaultdict
  3.  
  4.  
  5. def m1():
  6. tdict = {}
  7. tstr = 'one two one two three'*10
  8. for w in tstr.split():
  9. tdict[w] = tdict.get(w, 0) + 1
  10. res = tdict[w] - 1
  11.  
  12.  
  13. def m2():
  14. tlist = []
  15. tstr = 'one two one two three'*10
  16. for w in tstr.split():
  17. res = tlist.count(w)
  18. tlist.append(w)
  19.  
  20.  
  21. def m3():
  22. dftdict = defaultdict(int)
  23. tstr = 'one two one two three'*10
  24. for w in tstr.split():
  25. dftdict[w]+=1
  26. res = dftdict[w] - 1
  27.  
  28.  
  29.  
  30. print(timeit.timeit(m1, number=120000))
  31. print(timeit.timeit(m2, number=120000))
  32. print(timeit.timeit(m3, number=120000))
  33.  
Success #stdin #stdout 4.04s 9744KB
stdin
Standard input is empty
stdout
1.0738127902150154
1.8885362688452005
1.0611306596547365