我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。

我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。


当前回答

这是获取程序运行时间的最简单方法:

在程序末尾编写以下代码。

import time
print(time.clock())

其他回答

对于函数,我建议使用我创建的这个简单的修饰符。

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

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

Python程序执行度量的时间可能不一致,具体取决于:

可以使用不同的算法评估相同的程序运行时间因算法而异运行时间因实现而异运行时间因计算机而异基于小输入,运行时间不可预测

这是因为最有效的方法是使用“增长顺序”,并学习大“O”符号来正确地执行。

无论如何,您可以尝试使用以下简单算法来评估任何Python程序在每秒特定机器计数步骤中的性能:使其适应您想要评估的计划

import time

now = time.time()
future = now + 10
step = 4 # Why 4 steps? Because until here already four operations executed
while time.time() < future:
    step += 3 # Why 3 again? Because a while loop executes one comparison and one plus equal statement
step += 4 # Why 3 more? Because one comparison starting while when time is over plus the final assignment of step + 1 and print statement
print(str(int(step / 10)) + " steps per second")

我在查找两种不同方法的运行时间时遇到的问题,这两种方法用于查找所有<=一个数的素数。当在程序中进行用户输入时。

错误的方法

#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,但第一种方法(错误方法)是错误的。

使用line_profiler。

line_profiler将描述单个代码行执行所需的时间。分析器通过Cython在C语言中实现,以减少分析开销。

from line_profiler import LineProfiler
import random

def do_stuff(numbers):
    s = sum(numbers)
    l = [numbers[i]/43 for i in range(len(numbers))]
    m = ['hello'+str(numbers[i]) for i in range(len(numbers))]

numbers = [random.randint(1,100) for i in range(1000)]
lp = LineProfiler()
lp_wrapper = lp(do_stuff)
lp_wrapper(numbers)
lp.print_stats()

结果将是:

Timer unit: 1e-06 s

Total time: 0.000649 s
File: <ipython-input-2-2e060b054fea>
Function: do_stuff at line 4

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     4                                           def do_stuff(numbers):
     5         1           10     10.0      1.5      s = sum(numbers)
     6         1          186    186.0     28.7      l = [numbers[i]/43 for i in range(len(numbers))]
     7         1          453    453.0     69.8      m = ['hello'+str(numbers[i]) for i in range(len(numbers))]