fork download
  1. '''Time comparison of algorithms regarding this question:
  2. http://stackoverflow.com/questions/8344905/pythons-fastest-way-of-randomising-case-of-a-string/8344979#8344979'''
  3.  
  4. import timeit
  5. import __main__
  6. import random
  7.  
  8.  
  9. N = 100 #Number of executions
  10.  
  11. s = 'a'*1000
  12.  
  13. def test_f_initial():
  14. word_cap = ''
  15. for x in s:
  16. if random.randint(0,1):
  17. word_cap += x.upper()
  18. else:
  19. word_cap += x.lower()
  20. return word_cap
  21.  
  22.  
  23. def test_f_initial_local():
  24. ri = random.randint
  25. word_cap = ''
  26. for x in s:
  27. if ri(0,1):
  28. word_cap += x.upper()
  29. else:
  30. word_cap += x.lower()
  31. return word_cap
  32.  
  33.  
  34. def test_f_a():
  35. return ''.join(random.choice((str.upper,str.lower))(x) for x in s)
  36.  
  37.  
  38. def test_f_a_local():
  39. rc = random.choice
  40. return ''.join(rc((str.upper,str.lower))(x) for x in s)
  41.  
  42.  
  43. def test_f_aa():
  44. f_set = (str.upper, str.lower) #moving functions to the local namespace
  45. return ''.join(random.choice(f_set)(x) for x in s)
  46.  
  47.  
  48. def test_f_aa_local():
  49. rc = random.choice
  50. f_set = (str.upper, str.lower) #moving functions to the local namespace
  51. return ''.join(rc(f_set)(x) for x in s)
  52.  
  53.  
  54. def test_f_b():
  55. caps = s.upper()
  56. lowers = s.lower()
  57. return ''.join(x[random.randint(0,1)] for x in zip(lowers, caps))
  58.  
  59.  
  60. def test_f_b_local():
  61. caps = s.upper()
  62. lowers = s.lower()
  63. ri = random.randint
  64. return ''.join(x[ri(0,1)] for x in zip(lowers, caps))
  65.  
  66.  
  67. def test_f_ba():
  68. caps = s.upper()
  69. lowers = s.lower()
  70. return ''.join(random.choice(x) for x in zip(lowers, caps))
  71.  
  72.  
  73. def test_f_ba_local():
  74. rc = random.choice
  75. caps = s.upper()
  76. lowers = s.lower()
  77. return ''.join(rc(x) for x in zip(lowers, caps))
  78.  
  79.  
  80. names = dir(__main__)
  81. for name in names:
  82. attr = getattr(__main__,name)
  83. if hasattr(attr,'__call__'):
  84. if name.startswith('test_f_'):
  85. init_name = name + '_init'
  86. if hasattr(__main__, init_name):
  87. init = getattr(__main__,init_name)
  88. else:
  89. init = 'from __main__ import {name}'.format(name=name)
  90. t = timeit.Timer(stmt='{name}()'.format(name=name),
  91. setup=init)
  92.  
  93. time = t.timeit(N)
  94. print('{name}: {time}'.format(name=name,time=time))
Success #stdin #stdout 2.97s 6884KB
stdin
Standard input is empty
stdout
test_f_a: 0.2653028965
test_f_a_local: 0.249372959137
test_f_aa: 0.218335866928
test_f_aa_local: 0.210675001144
test_f_b: 0.405854225159
test_f_b_local: 0.396530151367
test_f_ba: 0.192643880844
test_f_ba_local: 0.18243598938
test_f_initial: 0.423223972321
test_f_initial_local: 0.408592939377