梁梦瑶 20190919-3 效能分析

此作业要求参见https://edu.cnblogs.com/campus/nenu/2019fall/homework/7628

git地址https://e.coding.net/hahaa/wf.git

要求0 以 战争与和平 作为输入文件,重读向由文件系统读入。连续三次运行,给出每次消耗时间、CPU参数。 (2分)

第一次运行时间

 

 

 第二次运行时间

 

 

 第三次运行时间

 

 

 

 

要求1 给出你猜测程序的瓶颈。你认为优化会有最佳效果,或者在上周在此处做过优化 (或考虑到优化,因此更差的代码没有写出) 。

要求 给出代码片断,并说明为什么你会认为此处是瓶颈,预计优化会有达到多好的效果
1.第一处我猜测获取文件中的单词个数的时候,由于上一周我的正则表达式出现了一点错误,导致统计字数不对,这周我修改了,修改方法是:先将所有单词转换为小写,然后再筛选。
但我认为此处还可以优化,原因是将大写字母转换为小写字母在进行筛选会很浪费时间。预计优化后运行时间会快那么一点点。

2.第二处是功能四的函数,为了输出格式问题,我又将单词统计的方法重新书写了一遍,如果考虑优化的话,这个地方还可以修改,可直接运用单词统计的封装函数
def redirect(txt): #功能四
    words = re.findall(r'[a-z0-9^-]+', txt.lower())
    user_counters=Counter(words)
    total=0
    for user_counter in user_counters:
        total+=1
    print("total %d words\n"%total)
    lsts=user_counters.most_common(10)
    for lst in lsts:
        print("%s  %d"%(lst[0],lst[1]))
 
 

要求2 通过 profile 找出程序的瓶颈。给出程序运行中最花费时间的3个函数(或代码片断)。要求包括截图。 (5分)

要求 分析为什么此处是瓶颈。

要求 profile需要得到函数的运行时间和次数。仅得到CPU和内存占用,不得分。

 

 

 

 

 代码片断:

def redirect(txt): #功能四
    words = re.findall(r'[a-z0-9^-]+', txt.lower())
    user_counters=Counter(words)
    total=0
    for user_counter in user_counters:
        total+=1
    print("total %d words\n"%total)
    lsts=user_counters.most_common(10)
    for lst in lsts:
        print("%s  %d"%(lst[0],lst[1]))

要求3 根据瓶颈,"尽力而为"地优化程序性能。

1.优化前:

 

def redirect(txt): #功能四
    words = re.findall(r'[a-z0-9^-]+', txt.lower())
    user_counters=Counter(words)
    total=0
    for user_counter in user_counters:
        total+=1
    print("total %d words\n"%total)
    lsts=user_counters.most_common(10)
    for lst in lsts:
        print("%s  %d"%(lst[0],lst[1]))

 

优化后:
将findall()函数进行了优化,函数进行封装。

def redirect(txt): #功能四
    words = re.findall(r'[a-zA-Z0-9^-]+', txt)
    coTotal(words)

2.优化前

def file_name(path): 
    path=path+'.txt'
    try:
        with open(path,encoding='utf-8') as f: 
            content=f.read()
    except FileNotFoundError: #异常处理,找不到文件,输出文件不存在
        msg="The file"+path+"does not exist."
        print(msg)
    else:
        words=re.findall(r'[a-z0-9^-]+',content.lower())
        coTotal(words)

优化后

def file_name(path): #功能二实现,输入不带后缀的文件名
    path=path+'.txt'
    with open(path,encoding='utf-8') as f: 
        content=f.read()
        words=re.findall(r'[a-z0-9^-]+',content.lower())
        coTotal(words)

要求4 再次 profile,给出在 要求1 中的最花费时间的3个函数此时的花费。要求包括截图。(2分)

 

 

 

三个函数此时的花费:

 

 再次测试三次:

 

 

 

 

转载于:https://www.cnblogs.com/summerkingy/p/11568471.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值