實務案例

Python 函式寫作

Shayne Miel

Software Architect @ Duo Security

函式計時

import time

def timer(func):
  """一個裝飾器,用來列印函式執行所花的時間。

  Args:
    func (callable): 被裝飾的函式。

  Returns:
    callable: 裝飾後的函式。
  """
Python 函式寫作
import time

def timer(func):
  """一個裝飾器,用來列印函式執行所花的時間。"""

# 定義要回傳的包裹函式。 def wrapper(*args, **kwargs):
# 呼叫 wrapper() 時,先取得現在時間。 t_start = time.time()
# 呼叫被裝飾的函式並儲存結果。 result = func(*args, **kwargs)
# 計算總花費時間並列印。 t_total = time.time() - t_start print('{} took {}s'.format(func.__name__, t_total))
return result
return wrapper
Python 函式寫作

使用 timer()

@timer
def sleep_n_seconds(n):
  time.sleep(n)
sleep_n_seconds(5)
sleep_n_seconds took 5.0050950050354s
sleep_n_seconds(10)
sleep_n_seconds took 10.010067701339722s
Python 函式寫作
def memoize(func):
  """將被裝飾函式的結果快取起來,便於快速查詢
  """

# 用 dict 依引數對應結果來儲存快取 cache = {}
# 定義要回傳的包裹函式。 def wrapper(*args, **kwargs): # 為 'kwargs' 建立可雜湊的 key。 kwargs_key = tuple(sorted(kwargs.items()))
# 若這組引數尚未出現過, if (args, kwargs_key) not in cache:
# 呼叫 func() 並儲存結果。 cache[(args, kwargs_key)] = func(*args, **kwargs)
return cache[(args, kwargs_key)]
return wrapper
Python 函式寫作
@memoize
def slow_function(a, b):
  print('Sleeping...')
  time.sleep(5)
  return a + b
slow_function(3, 4)
Sleeping...

7
slow_function(3, 4)
7
Python 函式寫作

何時使用裝飾器

  • 對多個函式加入共同行為
@timer
def foo():
  # 做一些運算

@timer
def bar():
  # 做其他運算

@timer
def baz():
  # 做別的事
Python 函式寫作

一起來練習吧!

Python 函式寫作

Preparing Video For Download...