Skip to content

Commit 0435817

Browse files
Add generators benchmark (#206)
1 parent 6e7b445 commit 0435817

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

pyperformance/data-files/benchmarks/MANIFEST

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ async_tree <local>
66
async_tree_cpu_io_mixed <local:async_tree>
77
async_tree_io <local:async_tree>
88
async_tree_memoization <local:async_tree>
9+
generators <local>
910
chameleon <local>
1011
chaos <local>
1112
crypto_pyaes <local>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
[project]
2+
name = "pyperformance_bm_generators"
3+
requires-python = ">=3.8"
4+
dependencies = ["pyperf"]
5+
urls = {repository = "https://github.com/python/pyperformance"}
6+
dynamic = ["version"]
7+
8+
[tool.pyperformance]
9+
name = "generators"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
Benchmark recursive generators implemented in python
3+
by traversing a binary tree.
4+
5+
Author: Kumar Aditya
6+
"""
7+
8+
from __future__ import annotations
9+
10+
from collections.abc import Iterator
11+
12+
import pyperf
13+
14+
15+
class Tree:
16+
def __init__(self, left: Tree | None, value: int, right: Tree | None) -> None:
17+
self.left = left
18+
self.value = value
19+
self.right = right
20+
21+
def __iter__(self) -> Iterator[int]:
22+
if self.left:
23+
yield from self.left
24+
yield self.value
25+
if self.right:
26+
yield from self.right
27+
28+
29+
def tree(input: range) -> Tree | None:
30+
n = len(input)
31+
if n == 0:
32+
return None
33+
i = n // 2
34+
return Tree(tree(input[:i]), input[i], tree(input[i + 1:]))
35+
36+
def bench_generators(loops: int) -> None:
37+
assert list(tree(range(10))) == list(range(10))
38+
range_it = range(loops)
39+
t0 = pyperf.perf_counter()
40+
for _ in range_it:
41+
for _ in tree(range(100000)):
42+
pass
43+
return pyperf.perf_counter() - t0
44+
45+
if __name__ == "__main__":
46+
runner = pyperf.Runner()
47+
runner.metadata['description'] = "Benchmark generators"
48+
runner.bench_time_func('generators', bench_generators)

0 commit comments

Comments
 (0)