三个提升Python运行速度的方法,都很实用!
今天总结三个提升Python运行速度的个提方法,只从代码本身考虑,运用提升运行速度并不会从编写C 扩展的行速代码、基于JIT的度的都实编译器技术考虑。
关于代码执行效率的个提第一个方法是减少频繁的方法访问,尤其是运用在多层循环内层、且循环次数较多的行速操作,差距尤为明显。度的都实
# 真是个提模块内全局变量 import math def compute_sqrt(nums): result = [] for n in nums: # 假如nums长度很大 # 1. math.sqrt 会被频繁访问 # 2. result.append 也会被频繁访问 result.append(math.sqrt(n)) return result看到在for循环里面,服务器租用涉及2个频繁的运用访问:
math.sqrt 会被频繁访问 result.append 也会被频繁访问因此第一步做如下更改:直接导入sqrt,而不是行速导入整个模块后再去引用sqrt
# 直接导入sqrt,而不是度的都实导入整个模块后再去引用sqrt from math import sqrt def compute_sqrt(nums): result = [] for n in nums: # 假如nums长度很大 # 1. math.sqrt 会被频繁访问 # 2. result.append 也会被频繁访问 result.append(sqrt(n)) return result然后再修改result.append,不用频繁访问append,个提使用标签apd指向它就行了:
# 直接导入sqrt,运用而不是行速导入整个模块后再去引用sqrt from math import sqrt def compute_sqrt(nums): result = [] apd = result.append for n in nums: # 假如nums长度很大 # 1. math.sqrt 会被频繁访问 # 2. result.append 也会被频繁访问 apd(sqrt(n)) return result第二个方法:查找局部变量的效率是最高的!!!对于频繁访问的变量应尽可能是局部变量,消除不必要的全局变量访问。所以对于上面代码,高防服务器sqrt还是模块级别的全局变量,所以修改为:
def compute_sqrt(nums): # 调整sqrt为局部变量 from math import sqrt result = [] apd = result.append for n in nums: # 假如nums长度很大 # 1. math.sqrt 会被频繁访问 # 2. result.append 也会被频繁访问 apd(sqrt(n)) return result第三个方法:不要做一些不必要的属性包装。比如@property必要时再用,能不用时就别用。如下对于属性y做@property装饰没有任何意义!只有在y有特定取值,比如只能取大于0的非负实数时再用此装饰才有意义。
class A: def __init__(self, x, y): self.x = x self.y = y @property def y(self): return self._y @y.setter def y(self, value): self._y = value因此修改为下面这样,删去多余的@property包装
class A: def __init__(self, x, y): self.x = x self.y = y以上就是Python代码提速的3条基本但却容易被忽略的有价值方法,希望对你有用。