我想测量执行一个函数所花费的时间。我没时间工作:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
我想测量执行一个函数所花费的时间。我没时间工作:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
当前回答
import time
def getElapsedTime(startTime, units):
elapsedInSeconds = time.time() - startTime
if units == 'sec':
return elapsedInSeconds
if units == 'min':
return elapsedInSeconds/60
if units == 'hour':
return elapsedInSeconds/(60*60)
其他回答
这是另一种方法:
>> from pytictoc import TicToc
>> t = TicToc() # create TicToc instance
>> t.tic() # Start timer
>> # do something
>> t.toc() # Print elapsed time
Elapsed time is 2.612231 seconds.
与传统方式相比:
>> from time import time
>> t1 = time()
>> # do something
>> t2 = time()
>> elapsed = t2 - t1
>> print('Elapsed time is %f seconds.' % elapsed)
Elapsed time is 2.612231 seconds.
安装:
pip install pytictoc
有关详细信息,请参阅PyPi页面。
时间也可以通过%timeit魔法函数测量,如下所示:
%timeit -t -n 1 print("hello")
n 1仅用于运行功能1次。
python cProfile和pstats模块为测量某些函数的时间提供了强大的支持,而无需在现有函数周围添加任何代码。
例如,如果您有python脚本timeFunctions.py:
import time
def hello():
print "Hello :)"
time.sleep(0.1)
def thankyou():
print "Thank you!"
time.sleep(0.05)
for idx in range(10):
hello()
for idx in range(100):
thankyou()
要运行探查器并生成文件的统计信息,只需运行:
python -m cProfile -o timeStats.profile timeFunctions.py
这是在使用cProfile模块来评测timeFunctions.py中的所有函数,并在timeStats.profile文件中收集统计信息。注意,我们不必向现有模块(timeFunctions.py)添加任何代码,这可以通过任何模块来完成。
一旦有了stats文件,就可以按如下方式运行pstats模块:
python -m pstats timeStats.profile
这将运行交互式统计浏览器,它为您提供了许多不错的功能。对于您的特定用例,您可以只检查函数的统计信息。在我们的示例中,检查两个函数的统计信息显示如下:
Welcome to the profile statistics browser.
timeStats.profile% stats hello
<timestamp> timeStats.profile
224 function calls in 6.014 seconds
Random listing order was used
List reduced from 6 to 1 due to restriction <'hello'>
ncalls tottime percall cumtime percall filename:lineno(function)
10 0.000 0.000 1.001 0.100 timeFunctions.py:3(hello)
timeStats.profile% stats thankyou
<timestamp> timeStats.profile
224 function calls in 6.014 seconds
Random listing order was used
List reduced from 6 to 1 due to restriction <'thankyou'>
ncalls tottime percall cumtime percall filename:lineno(function)
100 0.002 0.000 5.012 0.050 timeFunctions.py:7(thankyou)
这个假例子做不了什么,但给了你一个可以做什么的想法。这种方法最好的一点是,我不必编辑任何现有代码来获取这些数字,并且显然有助于分析。
测量时间(秒):
from timeit import default_timer as timer
from datetime import timedelta
start = timer()
# ....
# (your code runs here)
# ...
end = timer()
print(timedelta(seconds=end-start))
输出:
0:00:01.946339
给定要计时的函数,
测试.py:
def foo():
# print "hello"
return "hello"
使用timeit的最简单方法是从命令行调用它:
% python -mtimeit -s'import test' 'test.foo()'
1000000 loops, best of 3: 0.254 usec per loop
不要尝试使用time.time或time.clock(天真地)来比较函数的速度。他们会给出误导性的结果。
PS.不要将打印语句放在您希望计时的函数中;否则测量的时间将取决于终端的速度。