xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

如何使用 Python 运算符进行性能优化 All In One

如何使用 Python 运算符进行性能优化 All In One

为什么 Python 运算符 // 比 运算符 / 性能更好,运行速度更快呀❓

Why Python operator // is faster than operator /

questions

class Solution:
  def numberOfSteps(self, num: int) -> int:
    steps: int = 0
    while num > 0:
      steps += 1
      # num % 2 == 1
      if(num % 2):
        # 为什么 Python 运算符 // 比 运算符 / 性能更好,运行速度更快呀❓
        num -= 1
      else:
        num //= 2
    return steps

""" 

Runtime
Details
36ms
Beats 93.99%of users with Python3

Memory
Details
15.97mb
Beats 99.95%of users with Python3

"""

image

https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/submissions/

demos

Why // operator is faster than / operator in Python? ❌

Why floor division operator is faster than float division in Python? ✅

I tried some test cases and found that the // operator is faster than the / operator in Python, so what is going on behind the scenes?

  1. floor division //

Runtime 27 ms Beats 99.64%
Memory 16.3 MB Beats 62.99%

class Solution:
  def numberOfSteps(self, num: int) -> int:
    steps: int = 0
    while num > 0:
      steps += 1
      if(num % 2 == 0):
        # ❓
        num //= 2
      else:
        num -= 1
    return steps

  1. regular division /

Runtime 41 ms Beats 80.48%
Memory 16.4 MB Beats 24.29%

class Solution:
  def numberOfSteps(self, num: int) -> int:
    steps: int = 0
    while num > 0:
      steps += 1
      if(num % 2 == 0):
        num /= 2
      else:
        num -= 1
    return steps

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

Python 算术运算符

image

https://www.runoob.com/python3/python3-basic-operators.html

refs

https://stackoverflow.com/questions/76844578/why-floor-division-operator-is-faster-than-float-division-in-python3

https://stackoverflow.com/questions/36820113/python-2-why-is-floor-division-operator-faster-than-normal-division-operator



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-08-06 12:56  xgqfrms  阅读(12)  评论(5编辑  收藏  举报