# 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'): bench.start_group("%s, length=%s" % (group, length)) for name, before, after in ( ("ascii -> ascii", "a", "x"), ("ascii -> latin1", "a", "\xe9"), ("ascii -> UCS2", "a", "\u20AC"), ("ascii -> UCS4", "a", "\U0010ffff"), ("latin1 -> latin1", "\xe8", "\xe9"), ("UCS2 -> UCS2", "\u1234", "\u20AC"), ("UCS4 -> UCS4", "\U0010fffe", "\U0010ffff"), ): setup = ('length=%s; before = %r; text=%s; ' 'mapping=str.maketrans({before: %r})' % (length, before, text_setup, after)) bench.timeit('text.translate(mapping)', setup, name)