python 一个小小的性能提升

来源:互联网 发布:手机c语言编辑器中文 编辑:程序博客网 时间:2024/06/15 23:54

你可以通过将函数或方法的定位结果精确地存储至一个本地变量来获得一些性能提升。一个循环如:

for key in token:       dict[key] = dict.get(key, 0) + 1

每次循环都要定位dict.get。如果这个方法一直不变,可这样实现以获取小小的性能提升:

dict_get = dict.get  # look up the method oncefor key in token:       dict[key] = dict_get(key, 0) + 1

默认参数可在编译期被一次赋值,而不是在运行期。这只适用于函数或对象在程序执行期间不被改变的情况,比如替换

def degree_sin(deg):          return math.sin(deg * math.pi / 180.0)

def degree_sin(deg, factor = math.pi/180.0, sin = math.sin):    return sin(deg * factor)

1.2.2. python中local和global变量的规则是什么?

在 Python中,某个变量在一个函数里只是被引用,则认为这个变量是global。如果函数体中变量在某个地方会被赋值,则认为这个变量是local。如果一个global变量在函数体中 被赋予新值,这个变量就会被认为是local,除非你明确地指明其为global。
>>> x=1>>> def p():    print x    x=4    print x    >>> p()Traceback (most recent call last):  File "<pyshell#44>", line 1, in <module>    p()  File "<pyshell#43>", line 2, in p    print xUnboundLocalError: local variable 'x' referenced before assignment>>> def p():    print x    >>> p()1
原创粉丝点击