开发者

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

目录
  • 1. time.time()
  • 2. time.perf_counter() 推荐
  • 3. timeit.timeit ()
  • 4.装饰器统计运行耗时
  • 5. with 语句统计运行耗时
  • 6.延展: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))http://www.devze.com

以上方案中比较推荐使用的是 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 stawww.devze.comrt')
    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
js

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 tixhbgSkIwme

within time

timeout

within time

within time

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜