python:循环与理解
这个问题在这里已经有了答案:
您可以使用timeit
库,或者只使用time.time()
计时:
>>> from time import time
>>> def first():
... ftime = time()
... _foo = [x ** 2 for x in range(1, 101)]
... print "First", time()-ftime
...
>>> def second():
... ftime = time()
... _foo = []
... for x in range(1, 101):
... _b=[x**2]
... _foo+=_b
... print "Second", time()-ftime
...
>>> first()
First 5.60283660889e-05
>>> second()
Second 8.79764556885e-05
>>> first()
First 4.88758087158e-05
>>> second()
Second 8.39233398438e-05
>>> first()
First 2.8133392334e-05
>>> second()
Second 7.29560852051e-05
>>>
显然,列表理解运行得更快,约为2到3倍。
链接地址: http://www.djcxy.com/p/69945.html