我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。
我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。
当前回答
我在查找两种不同方法的运行时间时遇到的问题,这两种方法用于查找所有<=一个数的素数。当在程序中进行用户输入时。
错误的方法
#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,但第一种方法(错误方法)是错误的。
其他回答
对于使用Jupyter笔记本的数据人员
在单元格中,可以使用Jupyter的%%time魔术命令来测量执行时间:
%%time
[ x**2 for x in range(10000)]
输出
CPU times: user 4.54 ms, sys: 0 ns, total: 4.54 ms
Wall time: 4.12 ms
这将仅捕获特定单元的执行时间。如果您想捕获整个笔记本(即程序)的执行时间,可以在同一目录中创建一个新笔记本,并在新笔记本中执行所有单元格:
假设上面的笔记本名为example_notebook.ipynb。在同一目录中的新笔记本中:
# Convert your notebook to a .py script:
!jupyter nbconvert --to script example_notebook.ipynb
# Run the example_notebook with -t flag for time
%run -t example_notebook
输出
IPython CPU timings (estimated):
User : 0.00 s.
System : 0.00 s.
Wall time: 0.00 s.
要使用metakermit对Python 2.7的更新答案,您需要单调包。
代码如下:
from datetime import timedelta
from monotonic import monotonic
start_time = monotonic()
end_time = monotonic()
print(timedelta(seconds=end_time - start_time))
与@rogeriopvl的响应类似,我添加了一个轻微的修改,使用相同的库将长时间运行的作业转换为小时-分钟-秒。
import time
start_time = time.time()
main()
seconds = time.time() - start_time
print('Time Taken:', time.strftime("%H:%M:%S",time.gmtime(seconds)))
样本输出
Time Taken: 00:00:08
Python中最简单的方法:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
这假设程序运行至少需要十分之一秒。
打印:
--- 0.764891862869 seconds ---
只需使用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))