bpo-34210: Small improvements in heapq (refactoring)#8439
Closed
Amper wants to merge 1 commit intopython:masterfrom
Closed
bpo-34210: Small improvements in heapq (refactoring)#8439Amper wants to merge 1 commit intopython:masterfrom
Amper wants to merge 1 commit intopython:masterfrom
Conversation
Contributor
Author
|
@rhettinger I'm sorry, maybe my mistake is that I sent too many things in one commit. But still the main change that I wanted to focus on in paragraph 1. It's about code: if n >= size:
return sorted(iterable, key=key)[:n]In my opinion, using a slice here is unnecessary (because the number of elements is always known to be no greater than According to my measurements this branch in the code faster by 12-15% if you remove the slice using: def nlargest(n, iterable, key=None):
...
try:
size = len(iterable)
except (TypeError, AttributeError):
pass
else:
if n >= size:
return sorted(iterable, key=key, reverse=True)[:n]
...
def nlargest_new(n, iterable, key=None):
...
try:
size = len(iterable)
except (TypeError, AttributeError):
pass
else:
if n >= size:
return sorted(iterable, key=key, reverse=True)
...
if __name__ == "__main__":
...
from timeit import timeit
from random import randrange
data = [randrange(10000) for i in range(10000)]
test = """
for i in (10000, 5000, 1000, 500, 100, 10, 5, 1):
data = data[:i]
for n in (i, i + 1, i + 10, i + 100, i + 1000, i + 5000, i + 10000):
result = list(nlargest(n, data))
"""
print('before:', timeit(test, setup="from __main__ import data, nlargest", number=100000))
print('after:', timeit(test, setup="from __main__ import data, nlargest_new as nlargest", number=100000))Here are the results of one of the launches: I apologize for your time. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
https://bugs.python.org/issue34210