根据评论,我更新了代码:
import time
import math
def timeit1():
s = time.time()
for i in xrange(750000):
z=i**.5
print "Took %f seconds" % (time.time() - s)
def timeit2(arg=math.sqrt):
s = time.time()
for i in xrange(750000):
z=arg(i)
print "Took %f seconds" % (time.time() - s)
timeit1()
timeit2()
现在math.sqrt函数直接在一个局部参数,意味着它有最快的查找可能。
更新:python版本似乎重要这里。我曾经认为timeit1会更快,因为当python解析“i **。5”它知道,从句法上,哪个方法调用(__pow__或一些变体),所以它不必经过查询的开销即math.sqrt变体。但我可能错了:
Python 2.5:0.191000 vs. 0.224000
Python 2.6:0.195000 vs. 0.139000
也psyco似乎处理math.sqrt更好:
Python 2.5 Psyco 2.0:0.109000对0.043000
Python 2.6 Psyco 2.0:0.128000对0.067000
| Interpreter | x**.5, | sqrt, | sqrt faster, % |
| | seconds | seconds | |
|----------------+---------+---------+----------------|
| Python 3.2rc1+ | 0.32 | 0.27 | 19 |
| Python 3.1.2 | 0.136 | 0.088 | 55 |
| Python 3.0.1 | 0.155 | 0.102 | 52 |
| Python 2.7 | 0.132 | 0.079 | 67 |
| Python 2.6.6 | 0.121 | 0.075 | 61 |
| PyPy 1.4.1 | 0.083 | 0.0159 | 422 |
| Jython 2.5.1 | 0.132 | 0.22 | -40 |
| Python 2.5.5 | 0.129 | 0.125 | 3 |
| Python 2.4.6 | 0.131 | 0.123 | 7 |
#+TBLFM: $4=100*($2-$3)/$3;%.0f
在机器上产生的表结果:
$ uname -vms
Linux #42-Ubuntu SMP Thu Dec 2 02:41:37 UTC 2010 x86_64
$ cat /proc/cpuinfo | grep 'model name' | head -1
model name : Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz
重现结果:
> get source:git clone git://gist.github.com/783011.git gist-783011
> install tox:pip install tox>从tox.ini文件的目录运行tox。