Skip to content

Conversation

@zykron1
Copy link

@zykron1 zykron1 commented Sep 4, 2024

Added a built-in average function

gh-123658: Added a builtin average function

This pull request is based on #123658. I would like to propose that we add a builtin average function. I am aware this is potentially controversial and thus is probably not getting merged.

Benchmarking

I ran a benchmark on the following hardware:
iMac (Retina 4K, 21.5-inch, 2019)
3.6 GHz Quad-Core Intel Core i3
8 GB 2400 MHz DDR4
Radeon Pro 555X 2 GB

>>> from random import randint
>>> from statistics import mean
>>> from functools import wraps
>>> def timer(func):
...     @wraps(func)
...     def wrapper(*args, **kwargs):
...         start_time = time.time()
...         result = func(*args, **kwargs)
...         end_time = time.time()
...         duration = end_time - start_time
...         print(f"Function '{func.__name__}' took {duration:.4f} seconds to complete.")
...         return result
...     return wrapper
...     
>>> l = []
>>> for _ in range(1_000_000):
...     l.append(randint(-1_000_000, 1_000_000))
...     
>>> @timer
... def smean():
...     return mean(l)
...     
>>> @timer
... def bmean():
...     return avg(l)
...     
>>> bmean_result = bmean()
Function 'bmean' took 0.1531 seconds to complete.
>>> smean_result = smean()
Function 'smean' took 1.9991 seconds to complete.
>>> bmean_result == smean_result
True

As you can see, the new code is already faster than the current solution in the python standard library.

@ghost
Copy link

ghost commented Sep 4, 2024

All commit authors signed the Contributor License Agreement.
CLA signed

@hugovk
Copy link
Member

hugovk commented Sep 4, 2024

Please see #123658 (comment).

@hugovk hugovk closed this Sep 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants