基本上,我希望能够输出应用程序运行的经过时间。我想我需要使用某种 timeit 函数,但我不确定是哪一个。我正在寻找类似以下的东西...
START MY TIMER
code for application
more code
more code
etc
STOP MY TIMER
输出已用时间,在计时器启动和停止之间执行上述代码。想法?
最简单的方法是输入:
import time
start_time = time.time()
在开始时和
print("My program took", time.time() - start_time, "to run")
最后。
为了在不同平台上获得最佳效果:
from timeit import default_timer as timer
# START MY TIMER
start = timer()
code for application
more code
more code
etc
# STOP MY TIMER
elapsed_time = timer() - start # in seconds
timer()
在 Python 3.3 中是 time.perf_counter()
,在 Windows/其他平台上的旧版本中是 time.clock()/time.time()
。
如果您运行的是 Mac OS X 或 Linux,只需使用
time
实用程序:
$ time python script.py
real 0m0.043s
user 0m0.027s
sys 0m0.013s
如果没有,请使用
time
模块:
import time
start_time = time.time()
# ...
print time.time() - start_time, 's'
您可以使用系统命令
time
:
foo@foo:~# time python test.py
hello world!
real 0m0.015s
user 0m0.008s
sys 0m0.007s
在程序开始时获取系统当前时间,在程序结束时再次获取程序的结束时间,最后减去两个时间。
下面的代码描述了我们如何执行上述操作:
import time
start = time.time()
示例代码从这里开始
cnt = 1
for fun in range(10**11):
if (fun % 10**9 == 0):
print(cnt, fun)
cnt += 1
示例代码到此结束
end = time.time()
print('Time taken for fun program: ', end - start)
希望这一点永远清晰。
你不能直接获取开始和结束时的当前系统时间,然后用最终时间减去开始时间吗?
import time as t
def TimeTakenDecorator(func):
def wraper(*args,**kwargs):
start = t.time()
func(*args,**kwargs)
end = t.time()
print('Time taken for fun program: ', end - start)
return wraper
@TimeTakenDecorator
def hello(s):
for _ in range(100000000):
pass
print(s)
hello("test")
我会在装饰器中使用 Rad 的 answer,我要更改的主要内容是确保使用单调时钟,因此使用
t.time()
代替 t.monotonic()
,或者为了获得更高的精度 t.monotonic_ns()
。但这要求你使用 python v3.3 或更高版本,否则你可以尝试 this ctypes 变体获取单调时钟。
这是来自 python3 文档:
time.monotonic() → 浮动
返回单调时钟的值(以小数秒为单位),即不能倒退的时钟。时钟不受系统时钟更新的影响。返回值的参考点是未定义的,因此只有两次调用结果之间的差异才有效。
使用monotonic_ns()来避免float类型带来的精度损失。
3.3版本新增功能。
版本 3.5 中的更改:该功能现在始终可用并且始终在系统范围内。
版本 3.10 中进行了更改:在 macOS 上,该功能现在是系统范围内的。
time.monotonic_ns() → int
与 monotonic() 类似,但返回时间为纳秒。
3.7版本新增功能。
>>> import time as t
>>> t.time()
1666507313.6913335
>>> t.monotonic_ns()
2346741390948
>>> t.monotonic_ns()
2350236290783
>>> t.monotonic()
2353.851540444
>>> t.monotonic_ns()
2356366587038
>>> t.get_clock_info('time')
namespace(implementation='clock_gettime(CLOCK_REALTIME)', monotonic=False, adjustable=True, resolution=1e-09)
>>> t.get_clock_info('monotonic')
namespace(implementation='clock_gettime(CLOCK_MONOTONIC)', monotonic=True, adjustable=False, resolution=1e-09)
>>>
>>> t.monotonic()
3475.071162687
>>> t.monotonic_ns()/10**9
3475.877335106