我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。
我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。
当前回答
这是获取程序运行时间的最简单方法:
在程序末尾编写以下代码。
import time
print(time.clock())
其他回答
我在查找两种不同方法的运行时间时遇到的问题,这两种方法用于查找所有<=一个数的素数。当在程序中进行用户输入时。
错误的方法
#Sample input for a number 20
#Sample output [2, 3, 5, 7, 11, 13, 17, 19]
#Total Running time = 0.634 seconds
import time
start_time = time.time()
#Method 1 to find all the prime numbers <= a Number
# Function to check whether a number is prime or not.
def prime_no(num):
if num<2:
return False
else:
for i in range(2, num//2+1):
if num % i == 0:
return False
return True
#To print all the values <= n
def Prime_under_num(n):
a = [2]
if n <2:
print("None")
elif n==2:
print(2)
else:
"Neglecting all even numbers as even numbers won't be prime in order to reduce the time complexity."
for i in range(3, n+1, 2):
if prime_no(i):
a.append(i)
print(a)
"When Method 1 is only used outputs of running time for different inputs"
#Total Running time = 2.73761 seconds #n = 100
#Total Running time = 3.14781 seconds #n = 1000
#Total Running time = 8.69278 seconds #n = 10000
#Total Running time = 18.73701 seconds #n = 100000
#Method 2 to find all the prime numbers <= a Number
def Prime_under_num(n):
a = [2]
if n <2:
print("None")
elif n==2:
print(2)
else:
for i in range(3, n+1, 2):
if n%i ==0:
pass
else:
a.append(i)
print(a)
"When Method 2 is only used outputs of running time for different inputs"
# Total Running time = 2.75935 seconds #n = 100
# Total Running time = 2.86332 seconds #n = 1000
# Total Running time = 4.59884 seconds #n = 10000
# Total Running time = 8.55057 seconds #n = 100000
if __name__ == "__main__" :
n = int(input())
Prime_under_num(n)
print("Total Running time = {:.5f} seconds".format(time.time() - start_time))
上述所有情况下获得的不同运行时间都是错误的。对于我们正在接受输入的问题,我们必须在接受输入后才开始计时。这里,用户键入输入所花费的时间也与运行时间一起计算。
正确的方法
我们必须从开头删除start_time=time.time()并将其添加到主块中。
if __name__ == "__main__" :
n = int(input())
start_time = time.time()
Prime_under_num(n)
print("Total Running time = {:.3f} seconds".format(time.time() - start_time))
因此,两种方法单独使用时的输出如下:-
# Method 1
# Total Running time = 0.00159 seconds #n = 100
# Total Running time = 0.00506 seconds #n = 1000
# Total Running time = 0.22987 seconds #n = 10000
# Total Running time = 18.55819 seconds #n = 100000
# Method 2
# Total Running time = 0.00011 seconds #n = 100
# Total Running time = 0.00118 seconds #n = 1000
# Total Running time = 0.00302 seconds #n = 10000
# Total Running time = 0.01450 seconds #n = 100000
现在我们可以看到,与错误方法相比,总运行时间有显著差异。即使方法2在两种方法中的性能优于方法1,但第一种方法(错误方法)是错误的。
我尝试使用以下脚本找到时间差。
import time
start_time = time.perf_counter()
[main code here]
print (time.perf_counter() - start_time, "seconds")
我将这个timing.py模块放入我自己的站点包目录中,并在模块顶部插入导入计时:
import atexit
from time import clock
def secondsToStr(t):
return "%d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(t*1000,),1000,60,60])
line = "="*40
def log(s, elapsed=None):
print line
print secondsToStr(clock()), '-', s
if elapsed:
print "Elapsed time:", elapsed
print line
print
def endlog():
end = clock()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
def now():
return secondsToStr(clock())
start = clock()
atexit.register(endlog)
log("Start Program")
如果程序中有重要的阶段,我也可以在程序中调用timing.log。但仅包括导入计时就可以打印开始和结束时间,以及总运行时间。(请原谅我晦涩难懂的secondsToStr函数,它只是将浮点秒数设置为hh:mm:ss.sss格式。)
注意:上述代码的Python3版本可以在这里找到。
只需使用timeit模块。它同时适用于Python 2和Python 3。
import timeit
start = timeit.default_timer()
# All the program statements
stop = timeit.default_timer()
execution_time = stop - start
print("Program Executed in "+str(execution_time)) # It returns time in seconds
它在几秒钟内返回,您可以获得执行时间。这很简单,但您应该在启动程序执行的主函数中编写这些。如果您想获得执行时间,即使在出现错误时,也可以将参数“Start”设置为它,并在那里进行如下计算:
def sample_function(start,**kwargs):
try:
# Your statements
except:
# except statements run when your statements raise an exception
stop = timeit.default_timer()
execution_time = stop - start
print("Program executed in " + str(execution_time))
对于函数,我建议使用我创建的这个简单的修饰符。
def timeit(method):
def timed(*args, **kwargs):
ts = time.time()
result = method(*args, **kwargs)
te = time.time()
if 'log_time' in kwargs:
name = kwargs.get('log_name', method.__name__.upper())
kwargs['log_time'][name] = int((te - ts) * 1000)
else:
print('%r %2.22f ms' % (method.__name__, (te - ts) * 1000))
return result
return timed
@timeit
def foo():
do_some_work()
# foo()
# 'foo' 0.000953 ms