python装饰器decorator之计算函数运行时间的例子

本文介绍了一个使用Python装饰器来计算函数运行时间的例子。通过装饰器decorator,可以为函数file_read添加计时功能,记录打开文件'demo.txt'并逐行读取内容所消耗的时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值