Advertisement
here2share

# timeit_string_concatenation.py

Jan 21st, 2020
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.73 KB | None | 0 0
  1. # timeit_string_concatenation.py
  2.  
  3. import timeit
  4.  
  5. s = 'hello'
  6. t = 'world'
  7. str_dict = {'t': t, 's': s}
  8.  
  9. test = '''
  10. s + ' ' + t
  11. ' '.join((s, t))
  12. '%s %s' % (s, t)
  13. '{} {}'.format(s, t)
  14. '{0} {1}'.format(s, t)
  15. '{str1} {str2}'.format(str1=s, str2=t)
  16. '{s} {t}'.format(**globals())
  17. '%(s)s %(t)s' % str_dict
  18. '{s} {t}'.format(**str_dict)
  19. '''[1:-1].splitlines()
  20.  
  21. def fn(x=0):
  22.     if x:
  23.         return test[z]
  24.     return eval(test[z])
  25.  
  26. iterations = 10000
  27. for z in xrange(len(test)):
  28.     repeat = []
  29.     print fn(1)+' = "'+fn()+'"'
  30.     for n in xrange(10):
  31.         x = 'from __main__ import fn; fn()'
  32.         ttt = timeit.Timer(x)
  33.         x = ttt.timeit(iterations)
  34.         repeat += [x]
  35.     x = min(repeat)
  36.     print 'took {} seconds : best out of {}'.format(x,len(repeat))
  37.     print
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement