File: timeformat.py
import os, sys # pythons to test, command prefixes (Windows) pythons = ("py -3", "py -2", "C:\PyPy\pypy-1.9\pypy") # tests to run, command suffixes tests = ( # numbered vs auto-numbered fields: negligable effect #"-", #"-m timeit -n 10000 -r 5 \"s = '{}, {}, {}, {}' .format(123, 'spam', [1, 2], 7.89)\"", # str.format() "-", "-m timeit -n 10000 -r 5 \"s = '{0:}, {1:}, {2:}, {3:}' .format(123, 'spam', [1, 2], 7.89)\"", "-m timeit -n 10000 -r 5 \"s = '{:d}, {}, {}, {:f}' .format(123, 'spam', [1, 2], 7.89)\"", "-m timeit -n 10000 -r 5 \"s = '{:d}, {:<6s}, {}, {:.2f}'.format(123, 'spam', [1, 2], 7.89)\"", # str % fmt, equivalent cases "-", "-m timeit -n 10000 -r 5 \"s = '%s, %s, %s, %s' % (123, 'spam', [1, 2], 7.89)\"", "-m timeit -n 10000 -r 5 \"s = '%d, %s, %s, %f' % (123, 'spam', [1, 2], 7.89)\"", "-m timeit -n 10000 -r 5 \"s = '%d, %-6s, %s, %.2f' % (123, 'spam', [1, 2], 7.89)\"", # from http://sebastianraschka.com/Articles/2014_python_performance_tweaks.html#string_assembly "-", "-m timeit -n 10000 -r 5 \"x = ['a' + '1' + '2' for i in range(100)]\"", "-m timeit -n 10000 -r 5 \"x = ['a{}{}'.format('1', '2') for i in range(100)]\"", "-m timeit -n 10000 -r 5 \"x = ['a%s%s' % ('1', '2') for i in range(100)]\"", # same, but add func call: part of the slowdown in str.format() versus in-line expr? "-m timeit -n 10000 -r 5 -s \"def fmt(f, t): return f % t\"" " \"x = [fmt('a%s%s', ('1', '2')) for i in range(100)]\"" ) for python in pythons: print('=' * 80) print(os.popen(python + ' -c "import sys; print(sys.version)"').read()) for test in tests: if len(test) == 1: print(test * 80) else: cmd = python + ' ' + test print(cmd) print('\t' + os.popen(cmd).read()) if sys.platform.lower().startswith('win'): input('[Press Enter]') # stay open if clicked