您的位置:首页 > 其它

软件工程——第三次作业(2)

2017-09-26 18:14 465 查看
Part One

三次运行结果







Part Two

我猜测程序的瓶颈会存在在对累计单词的数量排序上,这里采用的是传递过来map键对,使用list进行比较然后进行排序,并且对统计的文章长度进行了分类,较长较短的文章走的是if的不同分支。所以,我认为在排序这里进行一些改动,会达到一定的优化效果。因为排序会有很多种方法,利用map键对不一定在时间或空间上是最好的选择,所以可以尝试一下别的排序方法,看能否使性能得到优化。

public static void sort(Map<String,Integer> map) {
List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(infoIds, new Comparator<Map.Entry<String,Integer>>() {//排序
public int compare(Map.Entry<String, Integer> a , Map.Entry<String,Integer> b) {
return (b.getValue()-a.getValue());
}
});
if(infoIds.size()>10) {
for(int i=0;i<10;i++) {//输出
Entry<String,Integer> id = infoIds.get(i);
System.out.println(id.getKey() + "\t\t" + id.getValue());
}
}else {
for(int i=0;i<infoIds.size();i++) {
Entry<String,Integer> id = infoIds.get(i);
System.out.println(id.getKey() + "\t\t" + id.getValue());
}
}
}


Part Three

对程序使用jvisualvm进行效能分析







以上效能截图显示,效能较差的部分有:

(1)sort函数的排序部分,可使用其它排序方法对其进行优化改进

public static void sort(Map<String,Integer> map) {
List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(infoIds, new Comparator<Map.Entry<String,Integer>>() {//排序
public int compare(Map.Entry<String, Integer> a , Map.Entry<String,Integer> b) {
return (b.getValue()-a.getValue());
}
});
if(infoIds.size()>10) {
for(int i=0;i<10;i++) {//输出
Entry<String,Integer> id = infoIds.get(i);
System.out.println(id.getKey() + "\t\t" + id.getValue());
}
}else {
for(int i=0;i<infoIds.size();i++) {
Entry<String,Integer> id = infoIds.get(i);
System.out.println(id.getKey() + "\t\t" + id.getValue());
}
}
}


分析原因:用map键对进行排序,并不是最优化的,可以选择更优化的排序方案。

(2)对文章长短进行分类的if语句,应该将控制是否继续进行的变量提到循环外面,这样可以节省一些时间。

if(infoIds.size()>10) {
for(int i=0;i<10;i++) {//输出
Entry<String,Integer> id = infoIds.get(i);
System.out.println(id.getKey() + "\t\t" + id.getValue());
}
}else {
for(int i=0;i<infoIds.size();i++) {
Entry<String,Integer> id = infoIds.get(i);
System.out.println(id.getKey() + "\t\t" + id.getValue());
}
}


分析原因:将变量提到外面,可以不用每次都运行后再判断,可直接判断,故可提高效能。

(3)在控制台中,是需要运行后根据提示,再输入文章名称,而输入文章名称的这部分人为时间会被计算在运行中;而在dos命令中直接在执行语句后输入文章名称,可略去人为输入时间,可提高程序的运行性能。

//从控制台输入文章名字
System.out.println("请输入文章名字");
String e = scanner.nextLine();
String  ee = "\\\\" + e;
wf1 c = new wf1();
String filePath = new File("File").getAbsolutePath()+ee;
String hh = c.getStringFrom(filePath);


分析原因:略去人为因素,可提高效能。

Part Four

对程序进行改进,将for中的循环变量提出为一个变量,不再每次循环时都重新加载,通过dos命令中的检测,可见整体运行时间减少了一些。

int i=0;
int j=infoIds.size();
if(j>10) {
for(;i<10;i++) {//输出
Entry<String,Integer> id = infoIds.get(i);
System.out.println(id.getKey() + "\t\t" + id.getValue());
}
}else {
for(;i<j;i++) {
Entry<String,Integer> id = infoIds.get(i);
System.out.println(id.getKey() + "\t\t" + id.getValue());
}
}




Part Five

改进后的效能截图









wf.exe链接路径

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