psyco
脚本的执行效率多少有点差强人意,虽然优化起来并不是难事,但如果有简单的方法,近乎不用修改源代码,那当然值得去关注一下。 psyco 的神奇在于它只需要在代码的入口处调用短短两行代码,性能就能提升 40% 或更多,真可谓是立竿见影!
如果你的客户觉得你的程序有点慢,敬请不要急着去优化代码, psyco 或许能让他立即改变看法。 psyco 堪称 Python 的 jit ,有许多潜力可以挖掘,如果剩下来给你优化性能的时间已经不多,请马上去阅读它的手册,有许多招儿轻松优化性能。
prifiler:
python -m profile prof1.py
profile.run("foo()")
4 function calls in 0.004 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.003 0.003 0.003 0.003 :0(setprofile)
1 0.001 0.001 0.001 0.001 <stdin>:1(say)
1 0.000 0.000 0.001 0.001 <string>:1(<module>)
0 0.000 0.000 profile:0(profiler)
1 0.000 0.000 0.004 0.004 profile:0(say())
ncalls函数的被调用次数
tottime函数总计运行时间,除去函数中调用的函数运行时间
percall函数运行一次的平均时间,等于tottime/ncalls
cumtime函数总计运行时间,含调用的函数运行时间
percall函数运行一次的平均时间,等于cumtime/ncalls
filename:lineno(function)函数所在的文件名,函数的行号,函数名
#带参数
profile.run("collectZol(searchTypes)")
timeit:
t = timeit.Timer("t = foo()\nprint t")
t.timeit()
及时跳出作用域来使得gc回收内存(注意避免递归调用时内存释放不了的问题)
#输出现存的对象数量
def outputGcInfo():
gc.collect()
print len(gc.get_objects())
把变量赋值为None来回收对象
>>> gc.collect();len(gc.get_objects())
0
3108
>>> x = ["1121"]
>>> gc.collect();len(gc.get_objects())
0
3109
>>> x = None
>>> gc.collect();len(gc.get_objects())
0
3108