Skip to content

impr: Optimized the format_number function - #258

Open
DebanKsahu wants to merge 2 commits into
psf:mainfrom
DebanKsahu:impr/performance
Open

impr: Optimized the format_number function#258
DebanKsahu wants to merge 2 commits into
psf:mainfrom
DebanKsahu:impr/performance

Conversation

@DebanKsahu

Copy link
Copy Markdown
Contributor

Description

  • So I was going through the code and encountered the function format_number where there is a branch which try to convert the number into 2^x format if possible. Previously the code iterate over the number till it become <2 and during that it count power but it can be easily done by simple bit manipulation.
  • A number can only be converted into 2^x if there is only one active bit means number & (number-1) will be 0 and power would be position of that active bit which is length-1.

@vstinner vstinner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@DebanKsahu

Copy link
Copy Markdown
Contributor Author

Sure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants