[Python] Pythonの実行時間を計算する

3.1 Python ランタイムの計算

インタープリタ型プログラミング言語として、Python は C や C++ などのコンパイルされた言語よりも開発が速く、実行は遅くなります。Python の実行速度を向上させる方法は、すべての Python 開発者が直面しなければならない問題です。
コードを最適化し、実行コードの実行効率を向上させる前に、Python コード ブロックの実行時間を知る必要があります。一般に、Python コード ブロックまたはプログラムの実行時間を計算するには、いくつかの方法があります。

3.1.1 datetimeモジュールによる計算

import datetime
import time

start = datetime.datetime.now()
# ↓ 以下是要计算时间的代码块
for _ in range(100):
    time.sleep(0.01)
# ↑ 以上是要计算时间的代码块
end = datetime.datetime.now()
print(end - start)

0:00:01.025894

3.1.2 時間モジュールによる計算 (Unix プラットフォームに推奨)

import time

start = time.time()
# ↓ 以下是要计算时间的代码块
for _ in range(100):
    time.sleep(0.01)
# ↑ 以上是要计算时间的代码块
end = time.time()
print(end - start)

1.0249037742614746

3.1.3 時間モジュールによる計算 (Windows プラットフォームで推奨)

import time

start = time.perf_counter()
# ↓ 以下是要计算时间的代码块
for _ in range(100):
    time.sleep(0.01)
# ↑ 以上是要计算时间的代码块
end = time.perf_counter()
print(end-start)

1.014091706

3.1.4 timeitモジュールによる計算

from timeit import timeit
import time
def myfun():
    for _ in range(100):
        time.sleep(0.01)
print(timeit(myfun, number=1))

1.028771429

注: このメソッドは関数の実行時間を計算するために使用でき、デフォルトは 100 万回です。使用する場合は数値パラメータに注意してください。一度だけ実行したい場合は、必ず 1 に設定してください。

Guess you like

Origin blog.csdn.net/crleep/article/details/131106545