python math.sqrt怎么扩大倍数_这在Python中更快:x ** 5或math.sqrt(x)?

根据评论,我更新了代码:

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值