python装饰器decorator之计算函数运行时间的例子:
#-*-coding:utf-8 -*- import time def decorator(func): def run_time(): start=time.clock()#time.clock()第一次调用的时候返回的是程序运行的实际时间 print 'start:',start,'\n' # result=func() func() stop=time.clock()#time.clock()第二次调用的时候返回的是第一次调用后,到这次调用的时间间隔 print 'run_time:',(stop-start) return run_time @decorator #装饰器(装饰器接收函数作为参数),相当于file_read=decorator(file_read),执行file_read()函数的时候, # 执行的过程变成了:把file_read()函数传递给decorator(func),decorator(func)接收一个函数即file_read(),然后按照 # decorator()函数的流程执行一遍 def file_read(): for line in open('demo.txt'): print 'file_read:',line file_read()