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

发布于 2024-11-25 17:45:34 字数 146 浏览 1 评论 0原文

我在 python 脚本中有以下代码:

def fun(): 
  #Code here

fun()

我想执行这个脚本,并找出执行时间(以分钟为单位)。我如何知道该脚本执行花费了多少时间?一个例子将非常感激。

I have the following code in a python script:

def fun(): 
  #Code here

fun()

I want to execute this script and also find out how much time it took to execute in minutes. How do I find out how much time it took for this script to execute ? An example would be really appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

天涯离梦残月幽梦 2024-12-02 17:45:34
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
startTime = datetime.now()

#do something

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

#Python 3: 
print(datetime.now() - startTime)
飘逸的'云 2024-12-02 17:45:34

您在 Linux 或 UNIX 上从命令行执行脚本吗?在这种情况下,你可以使用

time ./script.py

Do you execute the script from the command line on Linux or UNIX? In that case, you could just use

time ./script.py
九命猫 2024-12-02 17:45:34
import time
start = time.time()

fun()

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

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

fun()

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

# python 3
print('It took', time.time()-start, 'seconds.')
诗酒趁年少 2024-12-02 17:45:34

我通常做的是使用 time 库中的 clock()time()clock 测量解释器时间,而 time 测量系统时间。其他注意事项可以在文档中找到。

例如,

def fn():
    st = time()
    dostuff()
    print 'fn took %.2f seconds' % (time() - st)

或者,您可以使用timeit。我经常使用 time 方法,因为我可以很快地完成它,但如果您要对可隔离的代码片段进行计时,timeit 会派上用场。

timeit docs

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。如果如果您希望脚本运行时采用易于阅读的格式,无论是秒还是天,您可以将其转换为 timedeltastr

runtime = time() - st
print 'runtime:', timedelta(seconds=runtime)

这样就会打印出以下内容形式<代码>[D天[s],][H]H:MM:SS[.UUUUUU]。您可以查看 timedelta 文档

最后,如果您真正想要的是分析代码,Python 提供了 配置文件库也是如此。

What I usually do is use clock() or time() from the time library. clock measures interpreter time, while time measures system time. Additional caveats can be found in the docs.

For example,

def fn():
    st = time()
    dostuff()
    print 'fn took %.2f seconds' % (time() - st)

Or alternatively, you can use timeit. I often use the time approach due to how fast I can bang it out, but if you're timing an isolate-able piece of code, timeit comes in handy.

From the timeit docs,

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

Then to convert to minutes, you can simply divide by 60. If you want the script runtime in an easily readable format, whether it's seconds or days, you can convert to a timedelta and str it:

runtime = time() - st
print 'runtime:', timedelta(seconds=runtime)

and that'll print out something of the form [D day[s], ][H]H:MM:SS[.UUUUUU]. You can check out the timedelta docs.

And finally, if what you're actually after is profiling your code, Python makes available the profile library as well.

岁月无声 2024-12-02 17:45:34
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 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))
江南烟雨〆相思醉 2024-12-02 17:45:34
import time 

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

前面的代码对我来说没有问题!

import time 

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

The previous code works for me with no problem !

昔日梦未散 2024-12-02 17:45:34

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

然后我们开始,它会告诉您多少秒(或更短)执行该函数需要花费时间。如果它是一个简单的函数,那么您可以将其增加到 t.timeit(number=1000) (或任何数字!),然后将答案除以数字以获得平均值。

我希望这有帮助。

Use the timeit module. It's very easy. Run your example.py file so it is active in the Python Shell, you should now be able to call your function in the shell. Try it out to check it works

>>>fun(input)
output

Good, that works, now import timeit and set up a timer

>>>import timeit
>>>t = timeit.Timer('example.fun(input)','import example')
>>>

Now we have our timer set up we can see how long it takes

>>>t.timeit(number=1)
some number here

And there we go, it will tell you how many seconds (or less) it took to execute that function. If it's a simple function then you can increase it to t.timeit(number=1000) (or any number!) and then divide the answer by the number to get the average.

I hope this helps.

像你 2024-12-02 17:45:34

纯 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)。

文档

时间。perf_counter()→浮动

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

使用perf_counter_ns() 避免由于
浮动类型。

3.3 版中的新增功能。

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


Jupyter Notebook:%timeit & %time

如果您使用的是 Jupyter Notebook(例如 Google Colab ),您可以使用 IPython Magic Commands。

示例:

import time
import numpy as np
np.random.seed(42)

def fun(): 
    time.sleep(0.1+np.random.rand()*0.05)

然后在一个单独的单元格中,对函数计时多次

%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

您可以找到有关 Magic Commands 的更多信息 此处

Pure Python

Better yet is 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}")

Recommended by this guy as well (5:30).

Docs:

time.perf_counter()→ float

Return the value (in fractional seconds) of a performance counter,
i.e. a clock with the highest available resolution to measure a short
duration. It does include time elapsed during sleep and is
system-wide. The reference point of the returned value is undefined,
so that only the difference between the results of two calls is valid.

Use perf_counter_ns() to avoid the precision loss caused by the
float type.

New in version 3.3.

Changed in version 3.10: On Windows, the function is now system-wide.


Jupyter Notebook: %timeit & %time

If you are working in a Jupyter Notebook (such as Google Colab), you can use IPython Magic Commands.

Example:

import time
import numpy as np
np.random.seed(42)

def fun(): 
    time.sleep(0.1+np.random.rand()*0.05)

Then in a separate cell, to time the function multiple times:

%timeit fun()

Output:

10 loops, best of 5: 120 ms per loop

To time the function only once:

%time fun()

Output:

CPU times: user 0 ns, sys: 621 µs, total: 621 µs
Wall time: 114 ms

You can find more about Magic Commands here.

微暖i 2024-12-02 17:45:34

这是我使用函数式编程来实现这一点的方法 - 没有全局名称空间污染,复数的正确变形,只使用一个装饰器,所有这些都只有三个导入。我的所有脚本中都有此功能:

import time
from collections.abc import Callable
from functools import wraps


def time_function[**P, R](func: Callable[[P], R]) -> Callable[[P], R]:
    """
    Time functions using a decorator.

    Examples:

    >>>import time
    >>>
    >>>@time_function
    >>>def main() -> None:
    >>>    time.sleep(15)
    >>>
    >>>main()
    20:58:28: Starting script...
    The script took 15 seconds to run.

    >>>@time_function
    >>>def fn() -> None:
    >>>    time.sleep(61)
    >>>
    >>>fn()
    22:47:29: Starting script...
    Function "fn" took 1 minute and 1 second to run.
    """

    @wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        starting_time = time.perf_counter()
        f_name = func.__name__
        f_name = "main function" if f_name == "main" else f'function "{f_name}"'
        print(f"{time.strftime('%H:%M:%S', time.localtime())}: Starting {f_name}...")

        result = func(*args, **kwargs)

        elapsed_time = time.perf_counter() - starting_time
        hours, remainder = divmod(int(elapsed_time), 3600)
        minutes, seconds = divmod(remainder, 60)
        time_lst = [
            f"{n} {unit if n == 1 else unit + 's'}"
            for n, unit in ((hours, "hour"), (minutes, "minute"), (seconds, "second"))
            if n
        ]
        t_len = len(time_lst)

        if not t_len:
            time_str = "less than a second"
        elif t_len < 3:
            time_str = " and ".join(time_lst)
        else:
            time_str = f"{time_lst[0]}, {' and '.join(time_lst[1:])}"

        print(f"{f_name.capitalize()} took {time_str} to run.")

        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.

Here is the way I do this using functional programming - no global namespace pollution, proper inflection of plurals, only one decorator used, all with only three imports. I have this function in all my scripts:

import time
from collections.abc import Callable
from functools import wraps


def time_function[**P, R](func: Callable[[P], R]) -> Callable[[P], R]:
    """
    Time functions using a decorator.

    Examples:

    >>>import time
    >>>
    >>>@time_function
    >>>def main() -> None:
    >>>    time.sleep(15)
    >>>
    >>>main()
    20:58:28: Starting script...
    The script took 15 seconds to run.

    >>>@time_function
    >>>def fn() -> None:
    >>>    time.sleep(61)
    >>>
    >>>fn()
    22:47:29: Starting script...
    Function "fn" took 1 minute and 1 second to run.
    """

    @wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        starting_time = time.perf_counter()
        f_name = func.__name__
        f_name = "main function" if f_name == "main" else f'function "{f_name}"'
        print(f"{time.strftime('%H:%M:%S', time.localtime())}: Starting {f_name}...")

        result = func(*args, **kwargs)

        elapsed_time = time.perf_counter() - starting_time
        hours, remainder = divmod(int(elapsed_time), 3600)
        minutes, seconds = divmod(remainder, 60)
        time_lst = [
            f"{n} {unit if n == 1 else unit + 's'}"
            for n, unit in ((hours, "hour"), (minutes, "minute"), (seconds, "second"))
            if n
        ]
        t_len = len(time_lst)

        if not t_len:
            time_str = "less than a second"
        elif t_len < 3:
            time_str = " and ".join(time_lst)
        else:
            time_str = f"{time_lst[0]}, {' and '.join(time_lst[1:])}"

        print(f"{f_name.capitalize()} took {time_str} to run.")

        return result

    return wrapper

Sample input:

@time_function
def main() -> None:
    time.sleep(15)


if __name__ == '__main__':
    main()

Output:

20:58:28: Starting script...
The script took 15 seconds to run.

Sample input:

@time_function
def main() -> None:
    time.sleep(61)


if __name__ == '__main__':
    main()

Output:

22:47:29: Starting script...
The script took 1 minute and 1 second to run.
痴骨ら 2024-12-02 17:45:34

使用时间和日期时间包。

如果有人想执行这个脚本,并找出执行所需的时间(以分钟为单位)

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

上面的代码对我有用。我希望这有帮助。

use the time and datetime packages.

if anybody want to execute this script and also find out how much time it took to execute in minutes

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

The above code works for me. I hope this helps.

南巷近海 2024-12-02 17:45:34

对于Windows用户。

如果您想记录执行完整Python文件的时间,请使用下面给出的简单代码。

Measure-Command {python YourScript.py}

For Windows users.

If you want to record the time for executing a complete Python file, use the simple code given below.

Measure-Command {python YourScript.py}
木森分化 2024-12-02 17:45:34

导入 timeit 模块并将您想要计时的脚本部分定义为函数(例如 main())。


    import timeit
    
    BF = timeit.timeit('BruteForce_MemoryEfficiency.main()', setup='import BruteForce_MemoryEfficiency', number=1)
    
    print(BF)

该函数将执行 1 次(次数=1),并测量所需的时间。

Import timeit module and define the part of the script you want to time as function (e.g. main()).


    import timeit
    
    BF = timeit.timeit('BruteForce_MemoryEfficiency.main()', setup='import BruteForce_MemoryEfficiency', number=1)
    
    print(BF)

The function will be executed 1 time (number=1) and the time needed will be measured.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文