วัด overhead ของ decorator
หัวหน้าของคุณเขียน decorator ชื่อ check_everything() ขึ้นมา และยืนกรานให้คุณใช้กับฟังก์ชันของตัวเอง แต่คุณสังเกตว่าเมื่อใช้ decorator นี้ ฟังก์ชันทำงานได้ช้ากว่าเดิมมาก คุณจึงต้องโน้มน้าวหัวหน้าว่า decorator นี้เพิ่มเวลาประมวลผลมากเกินไป วิธีที่จะทำได้คือวัดเวลาที่ฟังก์ชันเวอร์ชันที่ถูก decorate ใช้ในการทำงาน แล้วเปรียบเทียบกับเวลาที่ฟังก์ชันต้นฉบับจะใช้หากไม่มี decorator นี่คือ decorator ที่เป็นปัญหา:
def check_everything(func):
@wraps(func)
def wrapper(*args, **kwargs):
check_inputs(*args, **kwargs)
result = func(*args, **kwargs)
check_outputs(result)
return result
return wrapper
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การเขียนฟังก์ชันใน Python
คำแนะนำการฝึกหัด
- เรียกใช้ฟังก์ชันต้นฉบับแทนเวอร์ชันที่ถูก decorate โดยใช้ attribute ที่คำสั่ง
wraps()ใน decorator ของหัวหน้าได้เพิ่มเข้ามาในฟังก์ชัน
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
@check_everything
def duplicate(my_list):
"""Return a new list that repeats the input twice"""
return my_list + my_list
t_start = time.time()
duplicated_list = duplicate(list(range(50)))
t_end = time.time()
decorated_time = t_end - t_start
t_start = time.time()
# Call the original function instead of the decorated one
duplicated_list = duplicate.____(list(range(50)))
t_end = time.time()
undecorated_time = t_end - t_start
print('Decorated time: {:.5f}s'.format(decorated_time))
print('Undecorated time: {:.5f}s'.format(undecorated_time))