This repository has been archived by the owner on Nov 5, 2022. It is now read-only.
/
bench_str_format_keywords.py
executable file
·81 lines (68 loc) · 2.07 KB
/
bench_str_format_keywords.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
"""
Micro-benchmark for the Python operation str.format().
Issues:
* http://bugs.python.org/issue14744 str.format()
* http://bugs.python.org/issue14687 str % args
"""
import pyperf
import sys
def run_benchmark(bench):
def timeit(stmt, setup):
name = "%s; %s" % (setup, stmt)
runner.timeit(name, stmt, setup)
use_unicode = sys.version_info >= (3,)
if use_unicode:
bmp = '"\\u20ac"'
short_ascii = '"abc"'
short_int = '123'
short_float = '12.345'
short_complex1 = '2j'
short_complex2 = '1+2j'
if use_unicode:
short_bmp = bmp + ' * 3'
SHORT_ARGS = (short_ascii, short_bmp, short_int)
else:
SHORT_ARGS = (short_ascii, short_int)
SHORT_ARGS += (short_float, short_complex1, short_complex2)
long_ascii = '"A" * 4096'
long_int = "2**4096 - 1"
if use_unicode:
long_bmp = bmp + ' * 4096'
LONG_ARGS = (long_ascii, long_bmp, long_int)
else:
LONG_ARGS = (long_ascii, long_int)
# Basic, short output
for arg in SHORT_ARGS:
timeit(
setup='fmt="{x}"; x=%s' % arg,
stmt='fmt.format(x=x)')
timeit(
setup='fmt="%%(x)s"; args={"x": %s}' % arg,
stmt='fmt % args')
# Basic, long output
for arg in LONG_ARGS:
timeit(
setup='fmt="{x}"; x=%s' % arg,
stmt='fmt.format(x=x)')
timeit(
setup='fmt="%%(x)s"; args={"x": %s}' % arg,
stmt='fmt % args')
# Prefix and suffix, short output
for arg in SHORT_ARGS:
timeit(
setup='fmt="x={x}."; x=%s' % arg,
stmt='fmt.format(x=x)')
timeit(
setup='fmt="x=%%(x)s."; args={"x": %s}' % arg,
stmt='fmt % args')
# Prefix and suffix, long output
for arg in LONG_ARGS:
timeit(
setup='fmt="x={x}."; x=%s' % arg,
stmt='fmt.format(x=x)')
timeit(
setup='fmt="x=%%(x)s."; args={"x": %s}' % arg,
stmt='fmt % args')
runner = pyperf.Runner()
run_benchmark(runner)