fork(2) download
  1. import timeit
  2. import __main__
  3. from cStringIO import StringIO
  4. from itertools import chain, repeat, takewhile
  5. from copy import copy
  6.  
  7.  
  8. N = 1000 #Number of executions
  9. L = 1000 #Length of initial list
  10. stringio = "StringIO('1'*L+'Z111')"
  11.  
  12.  
  13. def test_f_iter_plus_Z():
  14. stringio_loc = eval(stringio)
  15. i = takewhile(lambda x: x!='',iter(lambda: stringio_loc.read(1),'Z'))
  16. buf = ''.join(i) + 'Z'
  17.  
  18.  
  19. def test_f_iter_chain():
  20. stringio_loc = eval(stringio)
  21. i = takewhile(lambda x: x!='',iter(lambda: stringio_loc.read(1),'Z'))
  22. i = chain(i,repeat('Z',1))
  23. buf = ''.join(i)
  24.  
  25.  
  26. def take_until_included(stringio_loc):
  27. for s in iter(lambda: stringio_loc.read(1),''):
  28. yield s
  29. if s=='Z':
  30. return
  31.  
  32.  
  33. def test_f_generator():
  34. stringio_loc = eval(stringio)
  35. i = take_until_included(stringio_loc)
  36. buf = ''.join(i)
  37.  
  38.  
  39. def test_f_chunks():
  40. stringio_loc = eval(stringio)
  41. datalist = []
  42. for chunk in iter(lambda: stringio_loc.read(256),''):
  43. if 'Z' not in chunk:
  44. datalist.append(chunk)
  45. else:
  46. datalist.append(chunk[:chunk.find('Z')+1])
  47. break
  48. return ''.join(datalist)
  49.  
  50.  
  51. def test_f_chunks_generator():
  52. stringio_loc = eval(stringio)
  53. def gen():
  54. for chunk in iter(lambda: stringio_loc.read(256),''):
  55. if 'Z' not in chunk:
  56. yield chunk
  57. else:
  58. yield chunk[:chunk.find('Z')+1]
  59. break
  60. return ''.join(gen())
  61.  
  62.  
  63. names = dir(__main__)
  64. for name in names:
  65. attr = getattr(__main__,name)
  66. if hasattr(attr,'__call__'):
  67. if name.startswith('test_f_'):
  68. init_name = name + '_init'
  69. if hasattr(__main__, init_name):
  70. init = getattr(__main__,init_name)
  71. else:
  72. init = 'from __main__ import {name}; from cStringIO import StringIO;'.format(name=name)
  73. t = timeit.Timer(stmt='{name}()'.format(name=name),
  74. setup=init)
  75.  
  76. time = t.timeit(N)
  77. print('{name}: {time}'.format(name=name,time=time))
Success #stdin #stdout 3.48s 6748KB
stdin
Standard input is empty
stdout
test_f_chunks: 0.0398950576782
test_f_chunks_generator: 0.0435070991516
test_f_generator: 1.00860309601
test_f_iter_chain: 1.20431208611
test_f_iter_plus_Z: 1.17145586014