不同读入方式read(),readline(),readlines() 耗时对比

编写一个模块,该模块实现的功能如下:
1、引入grammar模块,通过引入的grammar模块生成句子,并把生成的句子写到名字为data.txt的文件中,写1亿次。
2、参考课上讲解的代码,通过装饰器测试在几种不同读取数据(读取自己生成的data.txt文件)的方式下的运行时间。

''' 伪代码
Step1. 编写主函数导入模块生成目标文件data.txt并调用read(),readline()和readlines()
三个函数读取目标文件data.txt,接收函数返回的消耗时间并输出
with open('data,txt', 'w') as file_object:
    for i in range(100000000):
        file_object.write(' '.join(sentence()) + '\n')
    read(file)
    readline(file)
    readlines(file)
step2. 编写三个辅助函数read(),readline()和readlines(),仅以readline举例
def readline(file)
    with open(file,'r') as f:
        while True:
            line = f.readline()
            if line == '':
                break
Step3. 编辑装饰器timer(),外层函数计时,并返回调用inner()函数;内层inner提示
用户进度并实现对read(),readline()和readlines()三个辅助函数的调用,并分别返
回消耗时间
def timer(read):
    def inner(x):
        start = time.time()
        read(x)
        end = time.time()
        return end - start
    return inner
Step4. 辅助函数前分别加装time@装饰器
@timer
def read(file): ...def readline(file):...def readlines(file):
Step5. 其他优化,如时间格式化输出等
'''

from grammar import sentence
import time
#装饰器函数
def timer(read):
    def inner(x):
        print('-RUNNING-')
        start = time.time()
        read(x)
        end = time.time()
        record = end - start
        return record
    return inner

@timer
def read(file)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值