Python计算函数执行时间(五种案例)

1. time.time()

在计算函数执行时间时,这种时最简洁的一种方式,用两个时间戳做减法。

import time


def func():
    print('func start')
    time.sleep(1)
    print('func end')


t = time.time()
func()
print(f'coast:{time.time() - t:.4f}s')

结果为:

func start
func end
coast:1.0003s

这种方法很简单,也很常用,但是如果想更精确的计算函数的执行时间,就会产生精度缺失。

2. time.perf_counter() 推荐

示例一中注释掉time.sleep(1),只统计两个 print 函数的执行时间:

import time


def func():
    print('func start')
    # time.sleep(1)
    print('func end')


t = time.time()
func()
print(f'coast:{time.time() - t:.8f}s')

func start
func end
coast:0.0000s

这就说明time.time() 函数的精度不是特别高,没法统计执行时间极短的函数耗时。

perf_counter 函数是在 python3.3 中新添加的,它返回性能计数器的值,返回值是浮点型,统计结果包括睡眠的时间,单个函数的返回值无意义,只有多次运行取差值的结果才是有效的函数执行时间。

import time


def func():
    print('func start')
    # time.sleep(1)
    print('func end')


t = time.perf_counter()
func()
print(f'coast:{time.perf_counter() - t:.8f}s')

结果

func start
func end
coast:0.00001500s

结果并不是 0 秒, 而是一个很小的值,这说明 perf_counter() 函数可以统计出 print 函数的执行耗时,并且统计精度要比 time.time() 函数要高,比较推荐作为计时器来使用。

3. timeit.timeit ()

timeit() 函数有 5 个参数,stmt=‘pass’, setup=‘pass’, timer=, number=1000000, globals=None。

  • stmt 参数是需要执行的语句,默认为 pass
  • setup 参数是用来执行初始化代码或构建环境的语句,默认为 pass
  • timer 是计时器,默认是 perf_counter()
  • number 是执行次数,默认为一百万
  • globals 用来指定要运行代码的命名空间,默认为 None。
import time
import timeit


def func():
    print('func start')
    time.sleep(1)
    print('func end')


print(timeit.timeit(stmt=func, number=1))

以上方案中比较推荐使用的是 time.perf_counter() 函数,它具有比较高的精度,同时还被用作 timeit 函数默认的计时器。

4.装饰器统计运行耗时

在实际项目代码中,可以通过装饰器方便的统计函数运行耗时。

import time


def cost_time(func):
    def fun(*args, **kwargs):
        t = time.perf_counter()
        result = func(*args, **kwargs)
        print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
        return result

    return fun


@cost_time
def test():
    print('func start')
    time.sleep(2)
    print('func end')


if __name__ == '__main__':
    test()

如果有使用异步函数的需求也可以加上:

import asyncio
import time
from asyncio.coroutines import iscoroutinefunction


def cost_time(func):
    def fun(*args, **kwargs):
        t = time.perf_counter()
        result = func(*args, **kwargs)
        print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
        return result

    async def func_async(*args, **kwargs):
        t = time.perf_counter()
        result = await func(*args, **kwargs)
        print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
        return result

    if iscoroutinefunction(func):
        return func_async
    else:
        return fun


@cost_time
def test():
    print('func start')
    time.sleep(2)
    print('func end')


@cost_time
async def test_async():
    print('async func start')
    await asyncio.sleep(2)
    print('async func end')


if __name__ == '__main__':
    test()
    asyncio.get_event_loop().run_until_complete(test_async())

使用装饰器来统计函数执行耗时的好处是对函数的入侵性小,易于编写和修改。

装饰器装饰函数的方案只适用于统计函数的运行耗时,如果有代码块耗时统计的需求就不能用了,这种情况下我们可以使用 with 语句自动管理上下文。

5. with 语句统计运行耗时

通过实现 enterexit 函数可以让我们在进入上下文和退出上下文时进行一些自定义动作,例如连接 / 断开数据库、打开 / 关闭文件、记录开始 / 结束时间等等,这里我们用来统计函数块的执行时间。

import asyncio
import time


class CostTime(object):
    def __init__(self):
        self.t = 0

    def __enter__(self):
        self.t = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f'cost time:{time.perf_counter() - self.t:.8f} s')


def test():
    print('func start')
    with CostTime():
        time.sleep(2)
        print('func end')


async def test_async():
    print('async func start')
    with CostTime():
        await asyncio.sleep(2)
        print('async func end')


if __name__ == '__main__':
    test()
    asyncio.get_event_loop().run_until_complete(test_async())

with 语句不仅可以统计代码块的执行时间,也可以统计函数的执行时间,还可以统计多个函数的执行时间之和,相比装饰器来说对代码的入侵性比较大,不易于修改,好处是使用起来比较灵活,不用写过多的重复代码。

Python中,有多种方法可以计算函数执行时间。其中一种简洁的方式是使用时间戳进行计算。你可以使用time模块中的time()函数获取当前时间戳,然后在函数执行前后分别获取时间戳,并计算它们的差值来得到函数执行时间。下面是一个示例代码: ```python import time def func(): print('func start') time.sleep(1) print('func end') t = time.time() func() print(f'coast:{time.time() - t:.4f}s') ``` 在这个示例中,我们首先使用time.time()获取当前时间戳t,然后调用func()函数函数中包含了一秒钟的延迟。最后,我们再次使用time.time()获取当前时间戳,并计算它们的差值,得到函数执行时间。输出结果会显示函数执行时间。 除了使用时间戳,还有其他几种方法可以计算函数执行时间。比如使用time模块中的perf_counter()函数、使用timeit模块中的timeit()函数、使用装饰器统计运行耗时以及使用with语句统计运行耗时等方法。你可以根据具体的需求选择适合的方法来计算函数执行时间。 #### 引用[.reference_title] - *1* *2* [Python计算函数执行时间五种案例)](https://blog.csdn.net/weixin_38924500/article/details/111679503)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [几种Python执行时间计算方法](https://blog.csdn.net/wangshuang1631/article/details/54286551)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值