📜  如何在 python 中获取函数的运行时(1)

📅  最后修改于: 2023-12-03 15:38:24.194000             🧑  作者: Mango

如何在 Python 中获取函数的运行时

在编写代码时,有时候我们需要了解函数的运行时间,以便我们进行性能分析等操作。那么,如何在 Python 中获取函数的运行时呢?本文将介绍三种方法。

1. 使用 time 模块

我们可以使用 Python 内置的 time 模块来获取函数的运行时间。time 模块提供了一个 time 函数,返回当前的时间戳。我们可以在函数执行前和执行后调用 time 函数,然后计算时间差,即可得到函数的运行时间。

import time

def foo():
    start = time.time()
    # 函数代码
    end = time.time()
    runtime = end - start
    print('函数运行时间为:', runtime)
2. 使用装饰器

装饰器是一种 Python 的语法,可以在函数执行前后添加一些操作。我们可以使用装饰器来获取函数的运行时间。

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        runtime = end - start
        print('函数运行时间为:', runtime)
        return result
    return wrapper

@timer
def foo():
    # 函数代码

使用装饰器可以避免我们为每个函数都添加获取运行时间的代码。

3. 使用 profile 和 pstats 模块

如果我们需要进行更加详细的性能分析,可以使用 Python 内置的 profile 和 pstats 模块。代码如下:

import cProfile
import pstats

def foo():
    # 函数代码

cProfile.run('foo()', 'result')
p = pstats.Stats('result')
p.sort_stats('cumulative').print_stats()

上述代码会将函数 foo 的运行结果存储到 result 文件中,并使用 pstats 模块对其进行分析。我们可以根据需要调整参数,比如修改 sort_stats 方法的第一个参数,来得到不同的分析结果。

以上就是三种在 Python 中获取函数的运行时的方法。根据需要,可以选择不同的方法进行性能分析。