(第三周)效能分析

此作业要求https://edu.cnblogs.com/campus/nenu/2018fall/homework/2145

 HTTP: https://git.coding.net/gongylx/wf.git

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

使用命令行进入程序所在文件夹,输入如下命令:

ptime wf -s < war_and_peace.txt

得到的运行时间分别如下:

1.第一次运行:

 

 

2.第二次运行:

 

 

3.第三次运行:

 

 

 

次数时间(s)
11.209
20.917
30.866
平均0.997

 

 

 

 

 

 

 

 

 

CPU参数: Intel(R) Core(TM) i5-4200H CPU @ 2.80GHz 2.80GHz

 

要求1:要求1 给出你猜测程序的瓶颈。你认为优化会有最佳效果,或者在上周在此处做过优化

这里分析遇到的时间瓶颈是由于处理文档中的标点符号方法造成的,这里采用将所有符号替换成空格符的方法,之前采用的是列举所有符号,用replace方法进行替换,代码如下:

def wf(text,flag):
    #for ch in '\r .,"':
        #text = text.replace(ch,' ')
    text = text.replace('\r',' ').replace(' ',' ').replace('.',' ').replace(',',' ').replace('"',' ')
    text = text.replace('\n',' ').lower().split()
    d = {}
    for word in text:
        if word == '':
            continue
        if word not in d:
            d[word] = 1
        else:
            d[word] += 1
    d_sorted = sorted(d.items(), key=lambda x: x[1], reverse=True)
    if flag == 0:
        print('total', len(d_sorted))
    else:
        print('total', len(d_sorted), 'words')
    for i in range(min(len(d_sorted), 10)):
        print('%-10s %-10s' % (d_sorted[i][0], d_sorted[i][1]))

要求2:通过profile 找出程序的瓶颈。给出程序运行中最花费时间的3个函数或代码片段

在命令行输入以下代码:

python -m cProfile -s time wf.py -s < war_and_peace.txt

得到耗时前三名结果如下图红框内所示:

 

要求3:根据瓶颈,“尽力而为”地优化程序性能

根据要求1中对程序瓶颈的猜想,优化后的代码如下所示:

def wf(text,flag):
    for ch in '\r .,"':
        text = text.replace(ch,' ')
    #text = text.replace('\r',' ').replace(' ',' ').replace('.',' ').replace(',',' ').replace('"',' ')
    text = text.replace('\n',' ').lower().split()
    d = {}
    for word in text:
        if word == '':
            continue
        if word not in d:
            d[word] = 1
        else:
            d[word] += 1
    d_sorted = sorted(d.items(), key=lambda x: x[1], reverse=True)
    if flag == 0:
        print('total', len(d_sorted))
    else:
        print('total', len(d_sorted), 'words')
    for i in range(min(len(d_sorted), 10)):
        print('%-10s %-10s' % (d_sorted[i][0], d_sorted[i][1]))

def Filename(filename,flag):
    with open(filename,'r', encoding='utf-8') as f:
        content = f.read()
        wf(content,flag)

 

要求4:再次profile,给出在要求1 中的最花费时间的3个函数此时的花费

再次输入代码:

python -m cProfile -s time wf.py -s < war_and_peace.txt

得到结果如下图所示:

1.第一次运行:

 

 2.第二次运行:

 

3.第三次运行:

 

次数时间(s)
10.425
20.442
30.430
平均0.432

 

 

 

 

 

 

 

 

CPU参数: Intel(R) Core(TM) i5-4200H CPU @ 2.80GHz 2.80GHz

对比可以看出平均时间由之前的0.997到现在的0.432,减少了0.565

 

要求5:程序运行时间

等待教师测评。

转载于:https://www.cnblogs.com/gongylx/p/9752285.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值