開始使用免費開始

量測裝飾器的額外開銷

你的主管寫了一個叫做 check_everything() 的裝飾器,自認非常厲害,並堅持要你把它用在你的函式上。不過,你發現一旦用它來裝飾你的函式,執行就會慢「非常」多。你需要說服主管,這個裝飾器讓你的函式多了太多處理時間。為了做到這點,你要量測套用裝飾器後的函式執行時間,並與未套用裝飾器時的執行時間比較。以下是問題中的裝飾器:

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 函式寫作

檢視課程

練習說明

  • 使用你主管的裝飾器中 wraps() 陳述式替被裝飾函式新增的屬性,改為呼叫原始函式,而不是被裝飾後的版本。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

@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))
編輯並執行程式碼