您的位置:首页 > 其它

软件工程-东北师大战-第三次作业(2)

2017-09-26 20:15 246 查看
程序下载地址: https://git.coding.net/xushaobin/xushaobin_gongneng_4_2.git
要求0

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



消耗时间:1.212s



消耗时间:1.302s



消耗时间:1.120s

平均消耗时间= (1.212+1.302+1.120)/3 =1.211(保留4位有效数字)

本机参数:



要求1

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

字符拼接原始代码(使用+=实现字符串拼接):

String strzong="";
string strReadline;
while ((strReadline = Console.ReadLine()) != null)
{
strzong += strReadline;
strzong += " ";
}
wf.Program.gongneng_4_2(strzong);


原始效果:耗时246.244s,效率低下。



修改过后的代码:

StringBuilder strzong = new StringBuilder(" ");
string strReadline;
while ((strReadline = Console.ReadLine()) != null)
{
strzong.Append(strReadline);
strzong.Append(" ");
}
wf.Program.gongneng_4_2(strzong.ToString());


修改效果:耗时1.462s,实现秒出结果,运算速度大幅提升。



要求2

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







程序的瓶颈:

System.Text.RegularExpressions.Regex.Replace(string,string)

System.Text.RegularExpressions.Regex.Replace(string,string,string)

所在代码:

rline = rline.ToLower();
rline = Regex.Replace(rline, @"[^a-zA-Z0-9\u4e00-\u9fa5\s]", " ");
rline = Regex.Replace(rline, "[!@#$%^&*()`,./;':\"<>`?...]", " ");
rline = new System.Text.RegularExpressions.Regex("[\\s]+").Replace(rline, " ");
string[] S = rline.Split(' ');


主要是正则表达式处理字符串消耗大量时间,考虑对其优化。

要求3

根据瓶颈,"尽力而为"地优化程序性能。 (5分)

处理字符串,想通过StringBuilder进行Replace处理,但是效果不太理想,个人觉得其实是可以优化的。编程尝试,但没实现太好的效果,所以代码恢复原来的。

尝试修改代码:

StringBuilder MyStringBuilder = new StringBuilder(lline);
MyStringBuilder = MyStringBuilder.Replace("'s", "").Replace("'m", "").Replace("'", "").Replace("—", "").Replace("?", "").Replace("!", "").Replace(",", "").Replace(":", "").Replace("\"", "").Replace("“", "").Replace("”", "").Replace(".", "").Replace(";", "").Replace(")", "").Replace("(", "").Replace("_", "");
MyStringBuilder = MyStringBuilder.Replace("1", "").Replace("2", "").Replace("3", "").Replace("4", "").Replace("5", "").Replace("6", "").Replace("7", "").Replace("8", "").Replace("9", "").Replace("0", "").Replace("*", "");
String rline = new System.Text.RegularExpressions.Regex("[\\s]+").Replace(MyStringBuilder.ToString(), " ");


要求4

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

这是通过StringBuilder进行Replace处理字符串的效能检测,并不理想,代码恢复原来版本,正在继续编程尝试优化。



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: