# Micro-benchmark for str.translate() # Use: "./python benchmark.py script translate_script.py" with: # https://bitbucket.org/haypo/misc/src/tip/python/benchmark.py def run_benchmark(bench): for group, text_setup in ( ("replace none", 'chr(ord(before)-1) * length'), ("replace 10%", '(before + "-"*9) * (length // 10)'), ("replace 50%", '(before + "-") * (length // 2)'), ("replace 90%", '(before*9 + "-") * (length // 10)'), ("replace all", 'before * length'), ): for length in ('10', '10**3', '10**6'): setup = ('length=%s; before = %r; text=%s; ' 'mapping=str.maketrans({before: %r})' % (length, 'a', text_setup, 'b')) bench.timeit('text.translate(mapping)', setup, "%s, length=%s" % (group, length))