Skip to content

Commit 547fad1

Browse files
committed
test: add simple python benches
1 parent 253b1be commit 547fad1

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

tests/benchmarks/test_bench_misc.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import pytest
2+
3+
4+
def count_even_fast(arr):
5+
"""Count the number of even numbers in an array."""
6+
even = 0
7+
for x in arr:
8+
if x % 2 == 0:
9+
even += 1
10+
return even
11+
12+
13+
def count_even_slow(arr):
14+
"""Count the number of even numbers in an array."""
15+
return sum(1 for x in arr if x % 2 == 0)
16+
17+
18+
@pytest.mark.parametrize(
19+
"func",
20+
[
21+
count_even_fast,
22+
count_even_slow,
23+
],
24+
)
25+
def test_count_even(func, benchmark):
26+
assert benchmark(func, range(10_000)) == 5000
27+
28+
29+
def sum_of_squares_for_loop_product(arr) -> int:
30+
total = 0
31+
for x in arr:
32+
total += x * x
33+
return total
34+
35+
36+
def sum_of_squares_for_loop_power(arr) -> int:
37+
total = 0
38+
for x in arr:
39+
total += x**2
40+
return total
41+
42+
43+
def sum_of_squares_sum_labmda_product(arr) -> int:
44+
return sum(map(lambda x: x * x, arr)) # noqa: C417
45+
46+
47+
def sum_of_squares_sum_labmda_power(arr) -> int:
48+
return sum(map(lambda x: x**2, arr)) # noqa: C417
49+
50+
51+
def sum_of_squares_sum_comprehension_product(arr) -> int:
52+
return sum(x * x for x in arr)
53+
54+
55+
def sum_of_squares_sum_comprehension_power(arr) -> int:
56+
return sum(x**2 for x in arr)
57+
58+
59+
@pytest.mark.parametrize(
60+
"func",
61+
[
62+
sum_of_squares_for_loop_product,
63+
sum_of_squares_for_loop_power,
64+
sum_of_squares_sum_labmda_product,
65+
sum_of_squares_sum_labmda_power,
66+
sum_of_squares_sum_comprehension_product,
67+
sum_of_squares_sum_comprehension_power,
68+
],
69+
)
70+
@pytest.mark.benchmark
71+
def test_sum_of_squares(func):
72+
assert func(range(1000)) == 332833500

0 commit comments

Comments
 (0)