目标:
1.编写运行函数,生成10个数的列表,没生成一个睡眠一会
2.编写装饰器,完成函数耗时计算
1.编写生成10个数的列表,并睡眠0.2s
代码如下:
[root@localhost python]# cat deco1.py
#!/usr/bin/env python# -*- coding: utf-8 -*-import timedef loop(): result = [] for i in xrange(10): result.append(i) time.sleep(0.2) return resultif __name__ == "__main__": print loop()
2.编写装饰器,实现计算loop()函数,生成10个数列表的耗时
代码如下:
#!/usr/bin/env python# -*- coding: utf-8 -*-import time #装饰器部分def deco(func): def timeit(): start = time.time() result = func() end = time.time() return (result, end - start) return timeit #引用装饰器@decodef loop(): result = [] for i in xrange(10): result.append(i) time.sleep(0.2) return resultif __name__ == "__main__": print loop()
•运行代码,测试效果
[root@localhost python]# python deco1.py([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 2.0052788257598877)
*提示:如果有多个函数,可以直接使用装饰器即可,如以下多个函数情况:
#!/usr/bin/env python# -*- coding: utf-8 -*-import timedef deco(func): def timeit(): start = time.time() result = func() end = time.time() return (result, end - start) return timeit@decodef loop(): result = [] for i in xrange(10): result.append(i) time.sleep(0.5) return result@decodef test(): t1 = [] for i in xrange(10): t1.append(i) time.sleep(0.8) return t1if __name__ == "__main__": print loop() print test()
附录:
装饰器,实现多个函数字体的统一设置
代码如下:
#!/usr/bin/env python# -*- coding: utf-8 -*-def set_color(func): def color(*args): return "\033[31m%s\033[0m" % func(*args) return color@set_colordef hello(): return "hello,world!"@set_colordef greet(): return "How are you?"@set_colordef welcome(word): return "Welcome to %s" % wordif __name__ == '__main__': print hello() print greet() print welcome('bj')