问题:找出一个python脚本完成执行所花费的时间

我在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.


回答 0

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)

回答 1

您是在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

回答 2

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

回答 3

我通常要做的是使用clock()time()time库中获取。clock测量口译员时间,同时time测量系统时间。其他注意事项可在docs中找到。

例如,

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

或者,您可以使用timeittime由于可以快速解决问题,因此我经常使用该方法,但是如果您正在计时可隔离的代码段,那么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。如果您希望脚本运行时以易于理解的格式显示,无论是秒还是天,都可以转换为a timedeltastr然后将其转换为:

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

然后打印出某种形式[D day[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.


回答 4

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 !


回答 5

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

回答 6

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


回答 7

使用时间和日期时间包。

如果有人要执行此脚本,并找出执行几分钟所需的时间

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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。