Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add generators benchmark #206

Merged
merged 3 commits into from
May 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyperformance/data-files/benchmarks/MANIFEST
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ async_tree <local>
async_tree_cpu_io_mixed <local:async_tree>
async_tree_io <local:async_tree>
async_tree_memoization <local:async_tree>
generators <local>
chameleon <local>
chaos <local>
crypto_pyaes <local>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[project]
name = "pyperformance_bm_generators"
requires-python = ">=3.8"
dependencies = ["pyperf"]
urls = {repository = "https://github.com/python/pyperformance"}
dynamic = ["version"]

[tool.pyperformance]
name = "generators"
48 changes: 48 additions & 0 deletions pyperformance/data-files/benchmarks/bm_generators/run_benchmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
Benchmark recursive generators implemented in python
by traversing a binary tree.

Author: Kumar Aditya
"""

from __future__ import annotations

from collections.abc import Iterator

import pyperf


class Tree:
def __init__(self, left: Tree | None, value: int, right: Tree | None) -> None:
self.left = left
self.value = value
self.right = right

def __iter__(self) -> Iterator[int]:
if self.left:
yield from self.left
yield self.value
if self.right:
yield from self.right


def tree(input: range) -> Tree | None:
n = len(input)
if n == 0:
return None
i = n // 2
return Tree(tree(input[:i]), input[i], tree(input[i + 1:]))

def bench_generators(loops: int) -> None:
assert list(tree(range(10))) == list(range(10))
range_it = range(loops)
t0 = pyperf.perf_counter()
for _ in range_it:
for _ in tree(range(100000)):
pass
return pyperf.perf_counter() - t0

if __name__ == "__main__":
runner = pyperf.Runner()
runner.metadata['description'] = "Benchmark generators"
runner.bench_time_func('generators', bench_generators)