Home  >  Article  >  Backend Development  >  How to calculate the execution time of a function in Python?

How to calculate the execution time of a function in Python?

WBOY
WBOYforward
2023-04-22 09:43:072354browse

Python development sometimes requires performance analysis and performance optimization. At this time, it is necessary to record some time-consuming function execution time issues, and then optimize the function logic.

What are the general methods in python3.

1. Use time.time()

This method is relatively simple, but if you want to calculate the execution time of the function more accurately, there will be a lack of precision, and there is no way to count extremely short times. The function takes 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>

2. Use time.perf_counter()

perf_counter is newly added in python3.3, returns the value of the performance counter, returns The value is a floating point type, and the statistical results include sleep time. The return value of a single function is meaningless. Only the result of running the difference multiple times is the effective function execution time.

<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>

3. Use timeit.timeit ()

<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>

4. Use decoration Device statistics

In the actual project code, the decorator can be used to conveniently count the running time of the function. The advantage of using decorators to count function execution time is that it is less intrusive to the function and easy to write and modify.

The decorator decorating function scheme is only suitable for counting the running time of the function. If there is a need for time-consuming statistics of code blocks, it cannot be used. In this case, you can use the with statement to automatically manage the context.

(1) Statistics of synchronous functions

<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>

(2) Statistics of asynchronous functions

<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>

5. With statement statistics

By implementing the enter and exit functions, you can perform some custom actions when entering and exiting the context, such as connecting or disconnecting the database, opening or closing files, Record the start or end time, etc., for example: we use it to count the execution time of function blocks.

The with statement can not only count the execution time of code blocks, but also the execution time of functions, and can also count the sum of the execution times of multiple functions. Compared with decorators, it is more intrusive to the code. , not easy to modify. The advantage is that it is more flexible to use and does not need to write too much repeated code.

<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>

The above is the detailed content of How to calculate the execution time of a function in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete