简体   繁体   English

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

[英]Find out time it took for a python script to complete execution

I have the following code in a python script:我在 python 脚本中有以下代码:

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.一个例子将不胜感激。

from datetime import datetime
startTime = datetime.now()

#do something

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

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

Do you execute the script from the command line on Linux or UNIX?您是否从 Linux 或 UNIX 上的命令行执行脚本? In that case, you could just use在这种情况下,您可以使用

time ./script.py
import time
start = time.time()

fun()

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

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

What I usually do is use clock() or time() from the time library.我通常做的是使用time库中的clock()time() clock measures interpreter time, while time measures system time. clock测量解释器时间,而time测量系统时间。 Additional caveats can be found in the docs .可以在docs中找到其他警告。

For example,例如,

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

Or alternatively, you can use timeit .或者,您可以使用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.我经常使用time方法,因为我可以快速完成它,但是如果您正在为一段可隔离的代码计时,那么timeit会派上用场。

From the timeit docs ,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()

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:然后要转换为分钟,您可以简单地除以 60。如果您希望脚本运行时采用易于阅读的格式,无论是秒还是天,您都可以转换为timedeltastr

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] .这将打印出[D day[s], ][H]H:MM:SS[.UUUUUU]的内容。 You can check out the timedelta docs .您可以查看timedelta 文档

And finally, if what you're actually after is profiling your code, Python makes available the profile library as well.最后,如果您真正想要的是分析您的代码,Python 也可以使用配置文件库

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 !以前的代码对我有用,没有问题!

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

Use the timeit module.使用 timeit 模块。 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. 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很好,可以,现在导入 timeit 并设置一个计时器

>>>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. go,它会告诉你执行 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.如果它是一个简单的 function 那么你可以将它增加到 t.timeit(number=1000) (或任何数字。)然后将答案除以数字以获得平均值。

I hope this helps.我希望这有帮助。

Pure Python纯Python

Better yet is time.perf_counter() :更好的是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 ).这个人也推荐( 5:30 )。

Docs : 文档

time. perf_counter() → float perf_counter() → float

Return the value (in fractional seconds) of a performance counter, ie 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.使用perf_counter_ns()可以避免浮点类型导致的精度损失。

New in version 3.3. 3.3 版中的新功能。

Changed in version 3.10: On Windows, the function is now system-wide.在 3.10 版中更改:在 Windows 上,function 现在是系统范围的。


Jupyter Notebook: %timeit & %time magic Jupyter Notebook: %timeit & %time魔法

If you are working in a Jupyter Notebook (such as Google Colab ), you can use IPython Magic Commands.如果您在 Jupyter Notebook(例如Google Colab )中工作,则可以使用 IPython 魔术命令。

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 :然后在一个单独的单元格中,多次计时 function

%timeit fun()

Output: Output:

10 loops, best of 5: 120 ms per loop

To time the function only once :只对 function 计时一次

%time fun()

Output: Output:

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

You can find more about Magic Commands here .您可以在此处找到有关魔术命令的更多信息。

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.我希望这有帮助。

Here is the way I do this using functional programming - no global namespace pollution, proper inflection of plurals, only one function call at the very top of your script, all with only three imports, compatible with older versions of Python.这是我使用函数式编程执行此操作的方法 - 没有全局命名空间污染,复数的正确变形,在脚本的最顶部只有一个 function 调用,只有三个导入,与旧版本的 Python 兼容。 I have this function in all my scripts:我的所有脚本中都有这个 function:

import atexit
import re
import time


def time_script() -> None:
    """Local namespace to keep starting time as a free variable."""

    starting_time = 0.0

    def time_script_enclosed() -> None:
        """Time your scripts easily. Run in the very beginning of the script."""
        nonlocal starting_time

        if not starting_time:
            starting_time = time.perf_counter()
            print(time.strftime('%H:%M:%S', time.localtime()), end="")
            print(": Starting script...")
            atexit.register(time_script_enclosed)
        else:
            runtime = int(time.perf_counter() - starting_time)
            # Formatting with proper inflection of plurals
            runtime = (
                time.strftime(
                    "%#H hours, %#M minutes and %#S seconds", time.gmtime(runtime)
                )
                .replace("0 hours, ", "")
                .replace("0 minutes and ", "")
            )
            
            runtime = re.sub(r"(?=^)1 hours", "1 hour", runtime)
            runtime = re.sub(r"(?=[^ ])1 minutes", "1 minute", runtime)
            runtime = re.sub(r"(?=[^ ])1 seconds", "1 second", runtime)

            print(f"The script took {runtime} to run.")

    time_script_enclosed()

Sample input:样本输入:

def main():
    time_script()
    time.sleep(15)


if __name__ == '__main__':
    main()

Output: Output:

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

Sample input:样本输入:

def main():
    time_script()
    time.sleep(61)


if __name__ == '__main__':
    main()

Output: Output:

22:47:29: Starting script...
The script took 1 minute and 1 second to run.

Import timeit module and define the part of the script you want to time as function (eg main()).导入timeit模块,定义你想要计时的部分脚本为function(例如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. function 将执行 1 次(number=1),并测量所需时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM