提高Python脚本的运行速度


// 源代码
#!/usr/bin/python

import psyco
import timeit

def slow_func():
for a in range(320):
for b in range(320):
for c in range(320):
if 320 == (a + b + c) and 106400 == (520 * a + 370 * b + 220 * c):
pass

if __name__ == '__main__':
fast_func = psyco.proxy(slow_func)
t1 = timeit.Timer("fast_func()", "from __main__ import fast_func")
t2 = timeit.Timer("slow_func()", "from __main__ import slow_func")
print "fast_func run %.2f sec" % t1.timeit(1)
print "slow_func run %.2f sec" % t2.timeit(1)


// 运行结果,提升了一个数量级(24倍)
fast_func run 0.16 sec
slow_func run 3.98 sec

你可能感兴趣的:(Python)