ใช้ time.clock() หรือ time.time() สำหรับการวัดเวลาความแม่นยำสูง เอกสารแนะนำสำหรับ benchmarking
ตัวอย่าง
import time
t0 = time.clock()
print("Hello")
t1 = time.clock() - t0
print("Time elapsed:", t1 - t0) # วินาที CPU (จุดทศนิยม)
ผลลัพธ์
Time elapsed: 0.0009403145040156798
หมายเหตุ: ระบบต่างๆ มีความแม่นยำต่างกันตาม internal clock (ticks ต่อวินาที) โดยทั่วไปดีกว่า 20ms นอกจากนี้ clock() คืนค่าต่างกันบนแพลตฟอร์มต่างกัน:
- Unix: คืน processor time ปัจจุบันเป็น float วินาที ใช้สำหรับ benchmarking Python หรือ timing algorithms
- Windows: คืน wall-clock seconds นับจากครั้งแรกที่เรียก ใช้ Win32
QueryPerformanceCounter()ความละเอียดดีกว่า 1 ไมโครวินาที