Python中计算函数执行时间的五种方法

 更新时间:2025年05月12日 09:43:57   作者:風の住む街~  
这篇文章主要为大家详细介绍了Python中统计函数执行时间的多种方法,例如time.time(),time.perf_counter(),timeit.timeit ()等,有需要的小伙伴可以了解下

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 语句统计运行耗时

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

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

6.延展:python实现函数超时退出

方法一

import time
import eventlet#导入eventlet这个模块
eventlet.monkey_patch()#必须加这条代码
with eventlet.Timeout(5,False):#设置超时时间为2秒
  time.sleep(4)
  print('没有跳过这条输出')
print('跳过了输出')

第二个方法 不太会用,用的不成功,不如第一个

import time
import timeout_decorator

@timeout_decorator.timeout(5)
def mytest():
    print("Start")
    for i in range(1,10):
        time.sleep(1)
        print("{} seconds have passed".format(i))

if __name__ == '__main__':
    mytest()

Python设置函数调用超时

import time
import signal
def test(i):
time.sleep(i%4)
print "%d within time"%(i)
return i
if __name__ == '__main__':
def handler(signum, frame):
raise AssertionError
i = 0
for i in range(1,10):
try:
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
test(i)
i = i + 1
signal.alarm(0)
except AssertionError:
print "%d timeout"%(i)

说明:

1、调用test函数超时监控,使用sleep模拟函数执行超时

2、引入signal模块,设置handler捕获超时信息,返回断言错误

3、alarm(3),设置3秒闹钟,函数调用超时3秒则直接返回

4、捕获异常,打印超时信息

执行结果

within time
within time
timeout
within time
within time
within time
timeout
within time
within time

到此这篇关于Python中计算函数执行时间的五种方法的文章就介绍到这了,更多相关Python计算函数执行时间内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python实现WebSocket服务端过程解析

    python实现WebSocket服务端过程解析

    这篇文章主要介绍了python实现WebSocket服务端过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • Python学习笔记之变量与转义符

    Python学习笔记之变量与转义符

    这篇文章主要介绍了Python学习笔记之变量与转义符,本文从零开始学习Python,知识点很细,有共同目标的小伙伴可以一起来学习
    2023-03-03
  • 如何解决django配置settings时遇到Could not import settings ''conf.local''

    如何解决django配置settings时遇到Could not import settings ''conf.loca

    这里记录一下在项目中遇到django配置settings时遇到Could not import settings 'conf.local'的解决方法,有同样问题的小伙伴们参考下吧
    2014-11-11
  • 在python中做正态性检验示例

    在python中做正态性检验示例

    今天小编就为大家分享一篇在python中做正态性检验示例,具有很的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • 深入理解Python虚拟机中描述器的实现原理

    深入理解Python虚拟机中描述器的实现原理

    这篇文章主要给大家介绍一个我们在使用类的时候经常使用但是却很少在意的黑科技——描述器的实现原理,文中的示例代码讲解详细,需要的可以参考一下
    2023-05-05
  • Python在画图时使用特殊符号的方法总结

    Python在画图时使用特殊符号的方法总结

    在制作图表时,如果遇到需要利用特殊符号进行表示时该怎么办呢?不用慌,这篇文章为大家总结了python画图中使用各种特殊符号的方式,需要的可以参考一下
    2022-04-04
  • python xpath获取页面注释的方法

    python xpath获取页面注释的方法

    今天小编就为大家分享一篇python xpath获取页面注释的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • Django实现发送邮件找回密码功能

    Django实现发送邮件找回密码功能

    在各大网站上,一定都遇到过找回密码的问题,通常采用的方式是通过发送带有验证码的邮件进行身份验证,本文将介绍通过Django实现邮件找回密码功能,需要的朋友可以参考下
    2019-08-08
  • 整理Python 常用string函数(收藏)

    整理Python 常用string函数(收藏)

    这篇文章主要介绍了整理Python 常用string函数(收藏)的相关资料,具有参考借鉴价值,需要的朋友可以参考下
    2016-05-05
  • Python安装及建立虚拟环境的完整步骤

    Python安装及建立虚拟环境的完整步骤

    在使用 Python 开发时,建议在开发环境和生产环境下都使用虚拟环境来管理项目的依赖,下面这篇文章主要给大家介绍了关于Python安装及建立虚拟环境的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-06-06

最新评论