math sqrt python_在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变量那样经历查找的开销。但我可能错了:

Python2.5:0.191000对0.224000

Python 2.6:0.195000对0.139000

同时,psyco似乎处理得更好:

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

要复制结果:获取源:^{}

安装^{}:pip install tox

使用tox.ini文件从目录中运行tox。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值