找出Python脚本完成执行所需的时间

174
我有一个Python脚本,其中包含以下代码:
def fun(): 
  #Code here

fun()

我想执行这个脚本,同时找出它执行所需的时间(以分钟为单位)。我该如何找出执行该脚本所需的时间?非常感谢提供示例。


5
在搜索"Python函数计时"的第一个结果中,这是链接:http://www.daniweb.com/software-development/python/code/216610 - Piskvor left the building
你还可以使用cProfile。它可以让你选择分别计时每个函数。 - Adam Rosenthal
12个回答

313
from datetime import datetime
startTime = datetime.now()

#do something

#Python 2: 
print datetime.now() - startTime 

#Python 3: 
print(datetime.now() - startTime)

8
Python新手,使用3.6.1版本。提醒一下,datetime模块不再有now属性。 - WizzleWuzzle
12
如果你使用 from datetime import datetime 而不是 import datetime,那么 datetime.now() 就可以正常工作(我刚在 Python 3.6.4 上确认了)。 - Paul Wicking
在Python 3.8中,情况是一样的,只是库中荒谬的模块datetime里有一个datetime类...我有点惊讶datetime类里没有datetime属性 -_- ..... - jave.web
什么是整洁:datetime(类)已经使用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
我认为time.perf_counter()比这个更好,已将其添加为答案。我不确定,所以我在这里询问了这个问题。 - zabop

153

您是在Linux或UNIX的命令行上运行脚本吗?如果是这种情况,您可以直接使用

time ./script.py

2
time -p ./script.py-p标志用于管道 - Joy
6
"Pipeline" 在这里是指什么?它有哪些作用? - ak3191
1
在Windows系统中,使用以下命令运行Python脚本:time python myScript.py。输出结果如下: 执行时间(秒):38.509970903396606 实际时间 0m38.792s 用户时间 0m0.015s 系统时间 0m0.046s - Aryashree Pritikrishna
2
@Joy 我认为你误读了 help time => "-p 以可移植的 Posix 格式打印时间摘要"。我认为你在这里 time [-p] pipeline 将一个选项和参数混淆了 :) pipeline 是一个参数(而不是选项) - 管道本身。 "执行 PIPELINE 并在其终止时打印有关执行 PIPELINE 所需的实际时间、用户 CPU 时间和系统 CPU 时间的摘要" 所以默认情况下是pipeline-p与此无关:) - jave.web
1
管道(|)在并行运行,而不是像我和许多其他人认为的那样串行运行 :) 因此,例如 time sleep 5 | sleep 10 只会测量10秒,因为这些睡眠实际上是并行运行的,整个管道大约在10秒内完成。 - jave.web

78
import time
start = time.time()

fun()

# python 2
print 'It took', time.time()-start, 'seconds.'

# python 3
print('It took', time.time()-start, 'seconds.')

7
在Python 3.x中,最后一行应该是print('It took {0:0.1f} seconds'.format(time.time() - start))。请注意不要改变原有的意思,并尽可能使语言更加通俗易懂。 - Chris Mueller
3
我曾在Python 2.7中工作。不过,我会把这个评论留在这里,这样人们就可以看到两个版本。 - Double AA
time.perf_counter() 我认为比 time.time() 更好。添加了这样的答案 - zabop

18
我通常使用来自于time库的clock()或time()函数来实现。clock()函数测量解释器时间,而time()函数则测量系统时间。更多注意事项可以在文档中找到。文档提供了详细内容。
例如:
def fn():
    st = time()
    dostuff()
    print 'fn took %.2f seconds' % (time() - st)

或者,你可以使用timeit。由于我能够快速地完成这个方法,所以我经常使用time方法,但是如果你正在计时一个可隔离的代码片段,timeit会很有用。
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 库


18
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))

1
50秒的打印输出为“0:0:50”。 - htzfun

17
import time 

startTime = time.time()
# Your code here !
print ('The script took {0} second !'.format(time.time() - startTime))

之前的代码对我来说没有任何问题!


12

使用timeit模块。它非常简单。运行你的example.py文件,使其在Python Shell中处于活动状态,现在你应该能够在shell中调用你的函数。尝试一下以检查它是否有效。

>>>fun(input)
output

好的,可以的,现在导入timeit并设置一个计时器。
>>>import timeit
>>>t = timeit.Timer('example.fun(input)','import example')
>>>

现在我们已经设置好了定时器,我们可以看到它花费的时间。
>>>t.timeit(number=1)
some number here

好的,让我翻译一下。这段内容涉及到it技术。它告诉我们如何计算一个函数执行所需的时间。如果这个函数比较简单,你可以将t.timeit(number=1000)(或者其他数字)增加,然后将答案除以该数字得到平均值。最终结果将显示需要执行多少秒才能完成函数。希望这对你有所帮助。


9

纯Python

更好的选择是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}")

这个人也推荐了这个家伙 (5:30)。

文档:

time.perf_counter()→ float

返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟来测量短时间间隔。它包括睡眠期间经过的时间,并且是系统范围内的。返回值的参考点未定义,因此仅两次调用结果之间的差异有效。

使用perf_counter_ns()避免由float类型引起的精度损失。

3.3版中新增。

3.10版中更改:在Windows上,该函数现在是系统范围内的。


Jupyter Notebook: %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

你可以在这里找到更多关于魔法命令的信息。


1

使用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))

上述代码对我来说有效。希望这可以帮到你。


1

这是我使用函数式编程的方法 - 没有全局命名空间污染,正确的复数形式,只使用了一个装饰器,仅用了四个导入,与从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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接