เพื่อวัดเวลาการทำงานของโปรแกรม ใช้ time.clock() หรือ time.time() เอกสาร Python แนะนำให้ใช้สำหรับ benchmarking วางการเรียกฟังก์ชันเหล่านี้รอบฟังก์ชันที่ต้องการวัด
ตัวอย่าง
import time
t0 = time.clock()
print("Hello")
t1 = time.clock() - t0
print("Time elapsed:", t1) # วินาที CPU (จุดทศนิยม)
ผลลัพธ์
Time elapsed: 0.0009403145040156798
ยังสามารถใช้โมดูล timeit สำหรับการวิเคราะห์สถิติเวลาทำงาน รันซ้ำหลายครั้งและรายงานเวลาที่เร็วที่สุด
ตัวอย่าง
def f(x):
return x * x
import timeit
timeit.repeat("for x in range(100): f(x)", "from __main__ import f", number=100000)
ผลลัพธ์
[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]