# Python-python中 ** 运算符为什么比sqrt()函数效率高很多？

`Python 2.6.6 (r266:84292, Dec  7 2011, 20:38:36) [GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> from timeit import Timer as t[0.1516878604888916, 0.15160799026489258, 0.15162897109985352]>>> from math import sqrt>>> t(lambda : sqrt(1234567890)).repeat() [0.27185297012329102, 0.2753138542175293, 0.27170610427856445]>>> t(lambda : 1234567890 ** 0.5).repeat() [0.15108108520507812, 0.15106606483459473, 0.15106606483459473]>>>`

### 评论（2）

2017-09-17 2 楼

import time
import math

def test1():
start = time.time()
for i in xrange(100000):
z = i**.5
print "x**0.5 took %f secs" % time.time() - start

def test2(f=math.sqrt): # 不要在for*里面*用math.sqrt, 查询函数的时间可能使结果有误差
start = time.time()
for i in xrange(100000):
z = f(i)
print "x**0.5 took %f secs" % time.time() - start

2017-06-03 1 楼

> s = dict(name="GOOG",shares=100,price=490.10)
> # s = {'name':'GOOG','shares':100,'price':490.10}
>

*程序员可能以这种方式创建字典来节省键入操作(无需在键名称两边添加引号).但是,这种创建字典的替代方法运行速度非常慢,因为他添加了额外的函数调用

1904 主题
5597 回复
18932 人气