今天总结了三种提高Python运行速度的方法。只考虑代码本身,不考虑编写C扩展代码或基于JIT的编译技术来提高运行速度。代码执行效率的第一个方法是减少频繁的方法访问,尤其是在多层循环的内层和循环次数较多的运算中,差距尤为明显。#真的是模块中的全局变量importmathdefcompute_sqrt(nums):result=[]forninnums:#如果nums的长度很大#1.math.sqrt会被频繁访问#2.result.append也会被频繁访问resultfor循环中看到.append(math.sqrt(n))returnresult,涉及2个频繁访问:math.sqrt会被频繁访问,result.append也会被频繁访问,所以第一步要做如下修改:直接importsqrt而不是importingThenreferencesqrtafterthewholemodule#直接importsqrt而不是importthewholemodule然后引用sqrtfrommathimportsqrtdefcompute_sqrt(nums):result=[]forninnums:#如果nums的长度很大#1.math.sqrt会被频繁访问#2.result.append也会被频繁访问result.append(sqrt(n))returnresult然后修改result.append,不用频繁访问append,直接用标签apd指向对它:#importsqrt直接而不是导入theentiremodule然后引用sqrtfrommathimportsqrtdefcompute_sqrt(nums):result=[]apd=result.appendforninnums:#如果nums的长度很大#1.math.sqrt会被频繁访问#2.result.append也会被频繁访问apd(sqrt(n))returnresult第二种方法:查找局部变量效率最高!!!经常访问的变量尽量是局部变量,杜绝不必要的全局变量访问。所以对于上面的代码,sqrt仍然是模块级别的全局变量,所以改为:defcompute_sqrt(nums):#将sqrt调整为局部变量frommathimportsqrtresult=[]apd=result.appendforninnums:#如果长度nums很大#1.math.sqrt会被频繁访问#2.result.append也会被频繁访问apd(sqrt(n))returnresult第三种方法:不要做不必要的属性包装。比如,该用的时候就用@property,不能用的时候就别用。像下面这样用@property修饰属性y没有任何意义!只有当y具有特定值时才有意义,例如,它只能取大于0的非负实数。classA:def__init__(self,x,y):self.x=xself.y=y@propertydefy(self):returnsself._y@y.setterdefy(self,value):self._y=value所以修改如下,删除多余的@propertypackagingclassA:def__init__(self,x,y):self。x=xself.y=y以上是3个基本但容易被忽视的Python代码加速的有价值的方法,希望对你有用。
