impr: Optimized the format_number function - #258
Open
DebanKsahu wants to merge 2 commits into
Open
Conversation
vstinner
reviewed
Sep 7, 2026
vstinner
left a comment
Member
There was a problem hiding this comment.
Can you please apply this change on your PR?
diff --git a/pyperf/tests/test_utils.py b/pyperf/tests/test_utils.py
index edf8549..52d08ad 100644
--- a/pyperf/tests/test_utils.py
+++ b/pyperf/tests/test_utils.py
@@ -130,15 +130,16 @@ class TestUtils(unittest.TestCase):
self.assertEqual(format_number(33 * 10 ** 4, 'unit'),
'330000 units')
- # powers of 10
+ # powers of 2
self.assertEqual(format_number(2 ** 10, 'unit'),
'1024 units')
self.assertEqual(format_number(2 ** 15, 'unit'),
'2^15 units')
self.assertEqual(format_number(2 ** 15),
'2^15')
- self.assertEqual(format_number(2 ** 10 + 1, 'unit'),
- '1025 units')
+ # not powers of 2
+ self.assertEqual(format_number(2 ** 15 - 1), '32767')
+ self.assertEqual(format_number(2 ** 15 + 1), '32769')
def test_format_filesize(self):
self.assertEqual(format_filesize(0),Currently, the tests don't cover well numbers which are close to power of 2 but are not power of 2.
Contributor
Author
|
Sure |
DebanKsahu
force-pushed
the
impr/performance
branch
from
September 7, 2026 17:13
079f5e8 to
6f480d6
Compare
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.
Description
format_numberwhere there is a branch which try to convert the number into2^xformat if possible. Previously the code iterate over the number till it become<2and during that it count power but it can be easily done by simple bit manipulation.2^xif there is only one active bit meansnumber & (number-1)will be0and power would be position of that active bit which islength-1.