def fun():
#Code here
fun()
我想执行这个脚本,同时找出它执行所需的时间(以分钟为单位)。我该如何找出执行该脚本所需的时间?非常感谢提供示例。
def fun():
#Code here
fun()
我想执行这个脚本,同时找出它执行所需的时间(以分钟为单位)。我该如何找出执行该脚本所需的时间?非常感谢提供示例。
from datetime import datetime
startTime = datetime.now()
#do something
#Python 2:
print datetime.now() - startTime
#Python 3:
print(datetime.now() - startTime)
from datetime import datetime
而不是 import datetime
,那么 datetime.now()
就可以正常工作(我刚在 Python 3.6.4 上确认了)。 - Paul Wickingdatetime
里有一个datetime
类...我有点惊讶datetime
类里没有datetime
属性 -_- ..... - jave.webdatetime
(类)已经使用ISO格式实现了__str__
,因此如果您将datetime实例转换为str()
或print()
它,格式将是YYYY-MM-DD HH:MM:SS.mmmmmm
,这相当于调用your_datetime.isoformat(sep=' ')
。参考:https://docs.python.org/3/library/datetime.html#datetime.datetime.__str__ - jave.web您是在Linux或UNIX的命令行上运行脚本吗?如果是这种情况,您可以直接使用
time ./script.py
-p
标志用于管道 - Joyhelp time
=> "-p 以可移植的 Posix 格式打印时间摘要
"。我认为你在这里 time [-p] pipeline
将一个选项和参数混淆了 :) pipeline 是一个参数(而不是选项) - 管道本身。 "执行 PIPELINE 并在其终止时打印有关执行 PIPELINE 所需的实际时间、用户 CPU 时间和系统 CPU 时间的摘要" 所以默认情况下是pipeline,-p
与此无关:) - jave.webtime sleep 5 | sleep 10
只会测量10秒,因为这些睡眠实际上是并行运行的,整个管道大约在10秒内完成。 - jave.webimport time
start = time.time()
fun()
# python 2
print 'It took', time.time()-start, 'seconds.'
# python 3
print('It took', time.time()-start, 'seconds.')
print('It took {0:0.1f} seconds'.format(time.time() - start))
。请注意不要改变原有的意思,并尽可能使语言更加通俗易懂。 - Chris Muellerdef fn():
st = time()
dostuff()
print 'fn took %.2f seconds' % (time() - st)
timeit
。由于我能够快速地完成这个方法,所以我经常使用time
方法,但是如果你正在计时一个可隔离的代码片段,timeit
会很有用。def test():
"Stupid test function"
L = []
for i in range(100):
L.append(i)
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
然后要转换成分钟,只需将其除以60即可。如果您想要以易于阅读的格式显示脚本运行时间,无论是以秒还是天为单位,可以将其转换为timedelta
并进行str
处理:
runtime = time() - st
print 'runtime:', timedelta(seconds=runtime)
这将打印出类似于 [D day[s], ][H]H:MM:SS[.UUUUUU]
的内容。您可以查看时间差文档。
最后,如果您实际上是想对代码进行分析,Python 还提供了profile 库。
import sys
import timeit
start = timeit.default_timer()
#do some nice things...
stop = timeit.default_timer()
total_time = stop - start
# output running time in a nice format.
mins, secs = divmod(total_time, 60)
hours, mins = divmod(mins, 60)
sys.stdout.write("Total running time: %d:%d:%d.\n" % (hours, mins, secs))
import time
startTime = time.time()
# Your code here !
print ('The script took {0} second !'.format(time.time() - startTime))
之前的代码对我来说没有任何问题!
使用timeit模块。它非常简单。运行你的example.py文件,使其在Python Shell中处于活动状态,现在你应该能够在shell中调用你的函数。尝试一下以检查它是否有效。
>>>fun(input)
output
>>>import timeit
>>>t = timeit.Timer('example.fun(input)','import example')
>>>
>>>t.timeit(number=1)
some number here
好的,让我翻译一下。这段内容涉及到it技术。它告诉我们如何计算一个函数执行所需的时间。如果这个函数比较简单,你可以将t.timeit(number=1000)(或者其他数字)增加,然后将答案除以该数字得到平均值。最终结果将显示需要执行多少秒才能完成函数。希望这对你有所帮助。
更好的选择是time.perf_counter()
:
t0 = time.perf_counter()
fun()
t1 = time.perf_counter()
print(t1-t0)
# and if you really want your answer in minutes:
print(f"In minutes: {(t1-t0)/60}")
文档:
time.
perf_counter()
→ float
返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟来测量短时间间隔。它包括睡眠期间经过的时间,并且是系统范围内的。返回值的参考点未定义,因此仅两次调用结果之间的差异有效。
使用
perf_counter_ns()
避免由float类型引起的精度损失。3.3版中新增。
3.10版中更改:在Windows上,该函数现在是系统范围内的。
%timeit
和 %time
魔法命令如果您正在使用 Jupyter Notebook(例如 Google Colab),则可以使用 IPython 魔法命令。
示例:
import time
import numpy as np
np.random.seed(42)
def fun():
time.sleep(0.1+np.random.rand()*0.05)
然后在另一个单元格中,多次计时函数 multiple:
%timeit fun()
输出:
10 loops, best of 5: 120 ms per loop
仅对函数进行一次计时:
%time fun()
输出:
CPU times: user 0 ns, sys: 621 µs, total: 621 µs
Wall time: 114 ms
你可以在这里找到更多关于魔法命令的信息。
使用time和datetime包。
如果有人想要执行此脚本并查找它执行了多长时间(以分钟为单位)
import time
from time import strftime
from datetime import datetime
from time import gmtime
def start_time_():
#import time
start_time = time.time()
return(start_time)
def end_time_():
#import time
end_time = time.time()
return(end_time)
def Execution_time(start_time_,end_time_):
#import time
#from time import strftime
#from datetime import datetime
#from time import gmtime
return(strftime("%H:%M:%S",gmtime(int('{:.0f}'.format(float(str((end_time-start_time))))))))
start_time = start_time_()
# your code here #
[i for i in range(0,100000000)]
# your code here #
end_time = end_time_()
print("Execution_time is :", Execution_time(start_time,end_time))
上述代码对我来说有效。希望这可以帮到你。
这是我使用函数式编程的方法 - 没有全局命名空间污染,正确的复数形式,只使用了一个装饰器,仅用了四个导入,与从3.6版本开始的Python兼容(如果删除类型提示)。我在所有脚本中都有这个函数:
import re
import time
from functools import wraps
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def time_function(func: Callable[P, R]) -> Callable[P, R]:
@wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
"""Time scripts using a decorator - no global namespace pollution, proper
inflection of plurals, only only one decorator call,
all with only four imports."""
starting_time = time.perf_counter()
name = func.__name__
name = "main function" if name == "main" else f'function "{name}"'
print(time.strftime("%H:%M:%S", time.localtime()) + f": Starting {name}...")
result = func(*args, **kwargs)
# Formatting with proper inflection of plurals, using regular expressions
runtime = time.strftime(
"%#H hours, %#M minutes and %#S seconds",
time.gmtime(time.perf_counter() - starting_time),
)
for old, new in (
(r"^0 hours, ", ""),
(r"^1 hours", "1 hour"),
(r"\b0 minutes and ", ""),
(r"\b1 minutes", "1 minute"),
(r"\b1 seconds", "1 second"),
(r"(?: and|,) 0 seconds", ""),
(r"^0 seconds", "less than a second"),
):
runtime = re.sub(old, new, runtime)
# Make the 0-second or 0-minute situation sound more natural
if ("second" in runtime) != ("minute" in runtime):
runtime = runtime.replace(", ", " and ")
print(f"{name} took {runtime} to run.".capitalize())
return result
return wrapper
示例输入:
@time_function
def main() -> None:
time.sleep(15)
if __name__ == '__main__':
main()
输出:
20:58:28: Starting script...
The script took 15 seconds to run.
示例输入:
@time_function
def main() -> None:
time.sleep(61)
if __name__ == '__main__':
main()
输出:
22:47:29: Starting script...
The script took 1 minute and 1 second to run.