练习题1. 请使用python, 对下面的函数进行处理,
def hello(name):
print "hello, %s" % name
在函数被调用时打印耗时详情
<function name: hello>
<function call begin>
hello, tom
<function call end>
[timecosts: 3.81469726562e-06s]
答案:
用到了装饰器,一个很简单的装饰器
贴出代码如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = '人生入戏'
import time
def calc_time(func):
def wrapper(*args,**kwargs):
print("<function name: %s>" % func.__name__)
print("<function call begin>")
start_time = time.clock()
func(*args,**kwargs)
time.sleep(1)
end_time = time.clock()
print("<function call end>")
print("time costs:%f" % (end_time - start_time))
return wrapper
@calc_time
def hello(name):
print("Hello, %s" % name)
hello("World")
运行结果:
<function name: hello>
<function call begin>
hello, world
<function call end>
time costs:0.999846