ใช้ time.clock() หรือ time.time() วัดเวลาที่ผ่านไประหว่างการทำงาน เอกสาร Python แนะนำสำหรับ benchmarking
ตัวอย่าง
import time
t0 = time.clock()
print("Hello")
t1 = time.clock() - t0
print("Time elapsed:", t1) # วินาที CPU (จุดทศนิยม)
ผลลัพธ์
Time elapsed: 1.2999999999999123e-05
ใช้โมดูล 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]