Pythonは、時間測定を行うためにtimeモジュールを提供しています。この記事では、Pythonで時間を測定する方法について説明します。

timeモジュール

timeモジュールには、time関数、sleep関数、clock関数などが含まれています。

time関数

time関数は、現在の時刻を取得するために使用されます。

import time

current_time = time.time()
print(current_time)

sleep関数

sleep関数は、指定された秒数だけプログラムを一時停止します。

import time

print("start")
time.sleep(5)
print("end")

clock関数

clock関数は、プログラムが実行された時間を計測するために使用されます。

import time

start_time = time.clock()
for i in range(1000000):
    pass
end_time = time.clock()
print(end_time - start_time)

perf_counter関数

timeモジュールのperf_counter関数を使用すると、高精度な時間測定ができます。

import time

start_time = time.perf_counter()
for i in range(1000000):
    pass
end_time = time.perf_counter()
print(end_time - start_time)

Conclusion

Pythonのtimeモジュールを使用すると、簡単に時間測定を行うことができます。さらに高精度な時間測定が必要な場合は、perf_counter関数を使用することができます。