Rus*_*hal 4 python performance time
以下是否有任何显着差异:
from time import time
start = time()
# some process
print time() - start
Run Code Online (Sandbox Code Playgroud)
和:
from timeit import timeit
def my_funct():
# some process
print timeit(my_funct, number=1)
Run Code Online (Sandbox Code Playgroud)
举个例子,我将使用Project Euler 1(因为它很容易理解/解决)
def pE1test1(): # using time()
from time import time
start = time()
print sum([n for n in range(1, 1000) if n%3==0 or n%5==0])
print time() - start
def pE1test2(): # using timeit
print sum([n for n in range(1, 1000) if n%3==0 or n%5==0])
from timeit import timeit
pE1test1()
print timeit(pE1test2, number=1)
Run Code Online (Sandbox Code Playgroud)
这输出:
>>>
233168
0.0090000629425
233168
0.00513921300363
Run Code Online (Sandbox Code Playgroud)
timeit和之间的主要区别是time什么?
timeit将使用您系统上最佳的定时功能.查看文档timeit.default_timer.
另外,timeit 关闭垃圾收集器.
另外,我相信你timeit错了.您应该按照文档中的最后一个示例传递一个字符串:
print timeit("pE1test2()","from __main__ import PE1test2",number=1)
Run Code Online (Sandbox Code Playgroud)
当然,另一个主要的区别在于,timeit为数千次迭代计算函数的执行时间是非常简单的(这是定时结果有意义的唯一时间).这降低了单次运行比其他运行花费更长时间的重要性(例如,由于您的系统资源被其他程序占用).
| 归档时间: |
|
| 查看次数: |
2647 次 |
| 最近记录: |