Skip to content

Commit d254df9

Browse files
authored
Add micro-benchmark for attrs classes (#33)
Microbenchmarks for this PR: python/mypy#11328
1 parent 735dff1 commit d254df9

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ Prerequisites:
2424
* Python 3.7 or later on Linux, macOS, or Windows
2525
* `mypyc` in `PATH`
2626
* A working Python C development environment
27+
* A python environment with mypy test-requirements.txt installed
2728

2829
Display the names of available benchmarks using `runbench.py --list`:
2930

microbenchmarks/attrs.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
from typing import List, Dict
2+
3+
import attr
4+
from benchmarking import benchmark
5+
6+
7+
@attr.s(auto_attribs=True)
8+
class C:
9+
n: int
10+
l: List[str]
11+
b: bool
12+
13+
def add(self, m: int) -> None:
14+
self.n = self.get() + m
15+
16+
def get(self) -> int:
17+
return self.n ^ 1
18+
19+
20+
@attr.s(auto_attribs=True)
21+
class C2:
22+
l: List[str]
23+
n: int
24+
25+
26+
@benchmark
27+
def create_attrs() -> None:
28+
N = 40
29+
a = [C(1, [], True)] * N
30+
l = ['x']
31+
for i in range(10000):
32+
for n in range(N):
33+
a[n] = C(n, l, False)
34+
b = []
35+
for n in range(N):
36+
b.append(C2(n=n, l=l))
37+
38+
39+
@benchmark
40+
def attrs_attr_access() -> None:
41+
N = 40
42+
a = []
43+
for n in range(N):
44+
a.append(C(n, [str(n)], n % 3 == 0))
45+
c = 0
46+
for i in range(100000):
47+
for o in a:
48+
c += o.n
49+
c += len(o.l)
50+
if o.b:
51+
c -= 1
52+
o.n ^= 1
53+
assert c == 80600000, c
54+
55+
56+
@benchmark
57+
def attrs_method() -> None:
58+
N = 40
59+
a = []
60+
for n in range(N):
61+
a.append(C(n, [str(n)], n % 3 == 0))
62+
c = 0
63+
for i in range(10000):
64+
for o in a:
65+
o.add(i & 3)
66+
c += o.n
67+
assert c == 3007600000, c
68+
69+
70+
@attr.s(auto_attribs=True, hash=True)
71+
class F:
72+
n: int
73+
s: str
74+
75+
76+
@benchmark
77+
def attrs_as_dict_key() -> None:
78+
d: Dict[F, int] = {}
79+
a = [F(i % 4, str(i % 3)) for i in range(100)]
80+
for i in range(1000):
81+
for f in a:
82+
if f in d:
83+
d[f] += 1
84+
else:
85+
d[f] = 1
86+
assert len(d) == 12, len(d)

0 commit comments

Comments
 (0)