此作业要求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)
1 1.209
2 0.917
3 0.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)
1 0.425
2 0.442
3 0.430
平均 0.432

 

 

 

 

 

 

 

 

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

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

 

要求5:程序运行时间

等待教师测评。