ホームページ  >  記事  >  バックエンド開発  >  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>

2. python3.3で新たに追加されたtime.perf_counter()

perf_counterを使用し、パフォーマンスカウンターの値を返します。 returns 値は浮動小数点型で統計結果にはスリープ時間も含まれる 単一関数の戻り値には意味がなく、差分を複数回実行した結果のみが実効的な関数実行時間となる

<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. 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. 装飾を使用するデバイス統計

実際のプロジェクト コードでは、デコレーターを使用して関数の実行時間を簡単にカウントできます。デコレータを使用して関数の実行時間をカウントする利点は、関数への侵入が少なく、記述と変更が簡単であることです。

デコレータ装飾関数スキームは、関数の実行時間をカウントする場合にのみ適しています。コード ブロックの時間のかかる統計が必要な場合は、使用できません。この場合、 with ステートメントを使用してコンテキストを自動的に管理します。

(1) 同期関数の統計情報

<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) 非同期関数の統計情報

<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. ステートメント統計を使用する

#enter 関数と exit 関数を実装すると、データベースの接続または切断、オープンまたはコンテキストの切断など、コンテキストに出入りするときにいくつかのカスタム アクションを実行できます。ファイルを閉じる、開始時間または終了時間を記録するなど。たとえば、機能ブロックの実行時間をカウントするために使用します。

with ステートメントは、コード ブロックの実行時間だけでなく、関数の実行時間や、複数の関数の実行時間の合計をカウントすることもできます。利点は、より柔軟に使用でき、繰り返しコードをあまり書く必要がないことです。

うわー

以上がPython で関数の実行時間を計算するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。