Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โมดูล timeit ใน Python: วัดประสิทธิภาพโค้ดอย่างแม่นยำ

Python มีหลายวิธีวัดเวลาการรันโค้ด โมดูล time วัดเวลาได้แต่ไม่รวม background processes ส่วน timeit รันโค้ดประมาณ 1 ล้านรอบ (ค่าเริ่มต้น) และนำเวลาต่ำสุดมาแสดง ให้ผลลัพธ์แม่นยำกว่า

การใช้งานผ่าน Command Line

C:\> python -m timeit "'-'.join(str(n) for n in range(200))"
1000 loops, best of 3: 290 usec per loop

การใช้งานในสคริปต์ Python

ตัวอย่างพื้นฐาน: timeit.timeit()

import timeit

# โค้ดที่ต้องการวัด
stmt1 = "y = 'x' * 5"
stmt2 = "xy = 'x' + 'x' + 'x' + 'x' + 'x'"

# วัด 10 ล้านรอบ
print(timeit.timeit(stmt1, number=10_000_000))
print(timeit.timeit(stmt2, number=10_000_000))

ตัวอย่าง: timeit.repeat() - รันหลายรอบเก็บรายการเวลา

import timeit

# รัน 5 รอบ แต่ละรอบ 10 ล้านครั้ง
result1 = timeit.repeat("y = 'x' * 3", number=10_000_000, repeat=5)
result2 = timeit.repeat("xy = 'x' + 'x' + 'x' + 'x' + 'x'", number=10_000_000, repeat=5)

print(result1)
print(result2)

ผลลัพธ์ตัวอย่าง:

[0.730, 0.721, 0.736, 0.729, 0.728]
[0.739, 0.738, 0.949, 0.735, 0.740]

การวัดหลายคำสั่ง (Multiple Statements)

ใช้ semicolon (;) คั่นคำสั่ง

import timeit

print(timeit.repeat("x = 2; x *= 2", number=100_000_000))
print(timeit.repeat("x = 1; x *= 4", number=100_000_000))

การใช้ setup parameter สำหรับฟังก์ชันกำหนดเอง

import timeit

def func1():
    return 1

def func2():
    return sum([-1, 0, 1, 1])

# ใช้ setup import ฟังก์ชัน
print(timeit.repeat("func1()", setup="from __main__ import func1"))
print(timeit.repeat("func2()", setup="from __main__ import func2"))

ผลลัพธ์:

[0.448, 0.441, 0.446]  # func1 เร็วกว่า
[1.584, 1.571, 1.547]  # func2 ช้ากว่า (ทำงานมากกว่า)

สรุป

  • ใช้ timeit.timeit() สำหรับการวัดครั้งเดียว
  • ใช้ timeit.repeat() สำหรับการวัดซ้ำเพื่อดูความเสถียร
  • ใช้ setup parameter สำหรับ import โค้ด/ฟังก์ชันภายนอก
  • ใช้ CLI python -m timeit สำหรับทดสอบเร็วๆ