如何获取Python程序执行的时间?

1722

我有一个用Python编写的命令行程序,运行时间比较长。我想知道它完成运行所需的精确时间。

我查看了timeit模块,但是它似乎只适用于小片段的代码。我想计时整个程序的运行时间。


太棒了,谢谢你的问题!下面的各位给出了很好的答案。帮我节省了时间。 - Qazi Ammar
39个回答

3

这是Paul McGuire的答案,对我很有效。以防万一有人运行出现问题。

import atexit
from time import clock

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

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)

def endlog():
    end = clock()
    elapsed = end-start
    log("End Program", secondsToStr(elapsed))

def now():
    return secondsToStr(clock())

def main():
    start = clock()
    atexit.register(endlog)
    log("Start Program")

从您的程序中导入文件后,调用timing.main()

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

3
这是获取程序经过时间的最简单方法:
在程序结尾处编写以下代码。
import time
print(time.clock())

6
main:1: DeprecationWarning: time.clock在Python 3.3中已被弃用,并将在Python 3.8中删除:请改用time.perf_counter或time.process_time - JayRizzo

1
要在Python 2.7中使用metakermit的更新答案,您需要monotonic包。
代码如下:
from datetime import timedelta
from monotonic import monotonic

start_time = monotonic()
end_time = monotonic()
print(timedelta(seconds=end_time - start_time))

1
下面是一行代码可以快速获取执行时间。
from time import perf_counter, sleep
_, _, exec_time = (s := perf_counter()), sleep(1), perf_counter()-s
print(exec_time)

1
如果你想用微秒来测量时间,那么你可以使用以下完全基于Paul McGuireNicojo答案的Python 3代码版本。我还为其添加了一些颜色:
import atexit
from time import time
from datetime import timedelta, datetime


def seconds_to_str(elapsed=None):
    if elapsed is None:
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    else:
        return str(timedelta(seconds=elapsed))


def log(txt, elapsed=None):
    colour_cyan = '\033[36m'
    colour_reset = '\033[0;0;39m'
    colour_red = '\033[31m'
    print('\n ' + colour_cyan + '  [TIMING]> [' + seconds_to_str() + '] ----> ' + txt + '\n' + colour_reset)
    if elapsed:
        print("\n " + colour_red + " [TIMING]> Elapsed time ==> " + elapsed + "\n" + colour_reset)


def end_log():
    end = time()
    elapsed = end-start
    log("End Program", seconds_to_str(elapsed))


start = time()
atexit.register(end_log)
log("Start Program")

log() => 打印时间信息的函数。

txt ==> log 的第一个参数,用于标记时间的字符串。

atexit ==> Python 模块,用于注册在程序退出时可以调用的函数。


0

在寻找两种不同方法计算所有小于等于某个数字的质数的运行时间时,我遇到了一个问题。当程序中输入用户输入时。

错误的方法

#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在两种方法中表现更好,但第一种方法(错误的方法)是错误的。

我用于返回小于等于某个数字的所有质数的方法2是错误的,它实际上返回的是小于等于该数字的所有奇数。这种情况仅适用于检查总运行时间时发生的错误。 - NELSON JOSEPH

0

默认情况下,Linux或Unix系统(在macOS上测试过)在终端上带有time命令,您可以使用它来运行Python脚本并获取运行脚本的realusersys时间信息。

然而,默认输出并不是很清晰(至少对我来说),而且默认的time命令甚至不接受任何选项作为参数来格式化输出。这是因为有两个版本time - 一个内置于bash中,提供最小版本,另一个位于/usr/bin/time

/usr/bin/time 命令接受额外的参数,如 -al-h-p-o。我最喜欢的是 -p,它可以将输出显示在新行中,如下所示:

real 2.18
user 17.92
sys 2.71

如何在Python或Bash Shell中实现? - EnthusiastiC
命令 time 是 Unix 系统特定的。这意味着它是 Linux 或 macOS 终端命令。 - Md Mazedul Islam Khan

-2
我定义了以下Python装饰器:
def profile(fct):
  def wrapper(*args, **kw):
    start_time = time.time()
    ret = fct(*args, **kw)
    print("{} {} {} return {} in {} seconds".format(args[0].__class__.__name__,
                                                    args[0].__class__.__module__,
                                                    fct.__name__,
                                                    ret,
                                                    time.time() - start_time))
    return ret
  return wrapper

并将其用于函数或类/方法中:

@profile
def main()
   ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接