From 8c7d573291e1a89044c0dc2c7bd352a994a75667 Mon Sep 17 00:00:00 2001 From: Chen Hanxiao Date: Mon, 24 Jul 2017 22:18:38 +0800 Subject: [PATCH] 07-closure-deco: add missing Example 7-17 An improved clock decorator(clockdeco2.py) Signed-off-by: Chen Hanxiao --- 07-closure-deco/clockdeco2.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 07-closure-deco/clockdeco2.py diff --git a/07-closure-deco/clockdeco2.py b/07-closure-deco/clockdeco2.py new file mode 100644 index 0000000..dd9f2f1 --- /dev/null +++ b/07-closure-deco/clockdeco2.py @@ -0,0 +1,22 @@ +# clockdeco2.py + +import time +import functools + +def clock(func): + @functools.wraps(func) + def clocked(*args, **kwargs): + t0 = time.time() + result = func(*args, **kwargs) + elapsed = time.time() - t0 + name = func.__name__ + arg_lst = [] + if args: + arg_lst.append(', '.join(repr(arg) for arg in args)) + if kwargs: + pairs = ['%s=%r' % (k, w) for k, w in sorted(kwargs.items())] + arg_lst.append(', '.join(pairs)) + arg_str = ', '.join(arg_lst) + print('[%0.8fs] %s(%s) -> %r ' % (elapsed, name, arg_str, result)) + return result + return clocked