>  기사  >  백엔드 개발  >  Python에서 함수의 실행 시간을 계산하는 방법은 무엇입니까?

Python에서 함수의 실행 시간을 계산하는 방법은 무엇입니까?

WBOY
WBOY앞으로
2023-04-22 09:43:072308검색

Python 개발에는 때때로 성능 분석과 성능 최적화가 필요합니다. 이때 시간이 많이 걸리는 함수 실행 시간 문제를 기록한 다음 함수 논리를 최적화해야 합니다.

python3의 일반적인 메서드는 무엇입니까?

1. time.time()을 사용하세요

이 방법은 비교적 간단하지만, 함수의 실행 시간을 더 정확하게 계산하고 싶다면 정확도가 부족하고 시간을 계산할 방법이 없습니다. 매우 짧은 기능을 소비합니다.

<pre class="brush:php;toolbar:false">import time    def func():  time.sleep(1)    t = time.time()  func()  print(f'耗时:{time.time() - t:.4f}s')    耗时:1.0050s</pre><pre class="brush:php;toolbar:false">import time  def func():  print('hello world')  t = time.perf_counter()  func()  print(f'耗时:{time.perf_counter() - t:.8f}s')  hello world  耗时:0.00051790s</pre>

2、使用time.perf_counter()

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

<pre class="brush:php;toolbar:false">timeit()函数有5个参数:  stmt 参数是需要执行的语句,默认为 pass  setup 参数是用来执行初始化代码或构建环境的语句,默认为 pass  timer 是计时器,默认是 perf_counter()  number 是执行次数,默认为一百万  globals 用来指定要运行代码的命名空间,默认为 None   import timeit  def func():  print('hello world')  print(f'耗时: {timeit.timeit(stmt=func, number=1)}')  hello world  耗时: 0.0007705999999999824</pre>

3、使用timeit.timeit ()

<pre class="brush:php;toolbar:false">import time   def coast_time(func):  def fun(*args, **kwargs):  t = time.perf_counter()  result = func(*args, **kwargs)  print(f'函数:{func.__name__} 耗时:{time.perf_counter() - t:.8f} s')  return result  return fun  @coast_time  def test():  print('hello world')  if __name__ == '__main__':  test()</pre>

4、使用装饰器统计

在实际项目代码中,可以通过装饰器方便的统计函数运行耗时。使用装饰器来统计函数执行耗时的好处是对函数的入侵性小,易于编写和修改。

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

(1)同步函数的统计

<pre class="brush:php;toolbar:false">import asyncio  import time  from asyncio.coroutines import iscoroutinefunction  def coast_time(func):  def fun(*args, **kwargs):  t = time.perf_counter()  result = func(*args, **kwargs)  print(f'函数:{func.__name__} 耗时:{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.__name__} 耗时:{time.perf_counter() - t:.8f} s')  return result  if iscoroutinefunction(func):  return func_async  else:  return fun  @coast_time  def test():  print('hello test')  time.sleep(1)  @coast_time  async def test_async():  print('hello test_async')  await asyncio.sleep(1)  if __name__ == '__main__':  test()  asyncio.get_event_loop().run_until_complete(test_async())   hello test  函数:test 耗时:1.00230700 s  hello test_async  函数:test_async 耗时:1.00572550 s</pre>

(2)异步函数的统计

<pre class="brush:php;toolbar:false">import asyncio  import time   class CoastTime(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'耗时:{time.perf_counter() - self.t:.8f} s')  def test():  print('hello test')  with CoastTime():  time.sleep(1)  async def test_async():  print('hello test_async')  with CoastTime():  await asyncio.sleep(1)  if __name__ == '__main__':  test()  asyncio.get_event_loop().run_until_complete(test_async()) hello test 耗时:1.00723310 s hello test_async 耗时:1.00366820 s</pre>

5、with语句统计

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

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

rrreee

2. time.perf_counter()를 사용하세요.🎜🎜perf_counter는 python3.3에 새로 추가되었습니다. 반환 값은 부동 소수점 형식입니다. 통계 결과에는 수면 시간이 포함되며, 단일 함수의 반환 값은 의미가 없으며 여러 번 실행한 결과의 차이만이 유효 함수 실행 시간입니다. 🎜🎜rrreee🎜🎜3. timeit.timeit()🎜🎜rrreee🎜🎜4. 데코레이터 통계를 사용하세요🎜🎜실제 프로젝트 코드에서는 데코레이터를 사용할 수 있습니다. 편리한 통계 기능 실행 시간. 함수 실행 시간을 계산하기 위해 데코레이터를 사용하면 함수에 대한 방해가 적고 작성 및 수정이 쉽다는 장점이 있습니다. 🎜🎜데코레이터를 사용하여 함수를 꾸미는 방식은 함수의 실행 시간을 계산하는 데에만 적합합니다. 코드 블록에 대한 시간 소모적인 통계가 필요한 경우에는 with 문을 사용할 수 없습니다. 자동으로 컨텍스트를 관리합니다. 🎜

(1) 동기 함수 통계

🎜rrreee🎜

(2) 비동기 함수 통계

🎜rrreee🎜🎜 5. 명령문 통계를 사용하여🎜🎜입력 및 종료 기능을 구현하면 컨텍스트에 들어가고 나갈 때 데이터베이스 연결 또는 연결 해제, 파일 열기 또는 닫기, 시작 또는 종료 시간 기록 등과 같은 일부 사용자 지정 작업을 수행할 수 있습니다. 예를 들어, 우리는 기능 블록의 실행 시간을 계산하는 데 사용합니다. 🎜🎜With 문은 코드 블록의 실행 시간뿐만 아니라 함수의 실행 시간도 계산할 수 있으며, 여러 함수의 실행 시간의 합도 계산할 수 있습니다. 데코레이터에 비해 코드에 더 방해가 되며 수정하기 쉽지 않으며, 사용하기가 더 유연하고 너무 많은 반복 코드를 작성할 필요가 없다는 장점이 있습니다. 🎜🎜아아앙🎜

위 내용은 Python에서 함수의 실행 시간을 계산하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제