JAVA8 函數(shù)編程
-都說java8 新的函數(shù)式編程特別是并行流式編程固耘,但是并行流的性能并不一定就好
long starttime1=System.currentTimeMillis();
//cur,bank,eat均為list
cul.parallelStream()
.forEach(tar->{
if(bank.parallelStream().
filter(poi->dwithin(poi.getLocation(),tar.getLocation(),500))
.collect(Collectors.toList()).size()>5 &&
eat.parallelStream().
filter(poi->dwithin(poi.getLocation(),tar.getLocation(),500))
.collect(Collectors.toList()).size()>5
)
res.add(tar);
}
);
System.out.println("并行計算耗時:"+String.valueOf(System.currentTimeMillis()-starttime1));
System.out.println(res.size());
System.out.println(res.get(0).getName());
res.clear();
long starttime=System.currentTimeMillis();
for(Pois tar:cul){
List ttmmpp1=new ArrayList();
List ttmmpp2=new ArrayList();
for(Pois poi:bank){
if(dwithin(poi.getLocation(),tar.getLocation(),500))
ttmmpp1.add(poi);
}
for(Pois poi:eat){
if(dwithin(poi.getLocation(),tar.getLocation(),500))
ttmmpp2.add(poi);
}
if(ttmmpp1.size()>5&&ttmmpp2.size()>5)
res.add(tar);
}
System.out.println("順序執(zhí)行耗時:"+String.valueOf(System.currentTimeMillis()-starttime));
System.out.println(res.size());
System.out.println(res.get(0).getName());
private static boolean dwithin(String A,String B,int radius) {
try {
Point a = (Point) reader.read("POINT(" + A.replace(",", " ") + ")");
Point b = (Point) reader.read("POINT(" + B.replace(",", " ") + ")");
return a.within(b.buffer(radius));
}catch(Exception e) {
}
return false;
}
沒有很復(fù)雜的深層循環(huán)题篷,兩層。結(jié)果可能讓人有些失望厅目。
將并行流改成順序流番枚,時間也少了50ms,這真的是讓人有點迷啊损敷。
并行和順序執(zhí)行對比測試
原因分析
首先我們看看并行流用了多少線程
System.out.println("ForkJoinPool.getCommonPoolParallelism() : " + ForkJoinPool.getCommonPoolParallelism());
輸出:一個線程葫笼。
咦,這拗馒。路星。。那設(shè)置高一點看看诱桂。
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "" + 8);
System.out.println("ForkJoinPool.getCommonPoolParallelism() : " + ForkJoinPool.getCommonPoolParallelism());
設(shè)置無效洋丐,參照如下博客修改了一番。
在run-edit configurations中設(shè)置JVM參數(shù)
-Djava.util.concurrent.ForkJoinPool.common.parallelism=64
其實這樣在CPU核心數(shù)量達不到的情況下確實提升水平有限挥等。
ps:https://blog.csdn.net/blueskybluesoul/article/details/82817007
按照這個教程修改后友绝,再次測試
修改后如下
final Long starttime2=System.currentTimeMillis();
ForkJoinPool myPool = new ForkJoinPool(8);
myPool.submit(() ->cul.parallelStream()
.forEach(tar->{
//System.out.println(tar.getName());
if(bank.stream().
filter(poi->dwithin(poi.getLocation(),tar.getLocation(),300))
.collect(Collectors.toList()).size()>5 &&
eat.stream().
filter(poi->dwithin(poi.getLocation(),tar.getLocation(),300))
.collect(Collectors.toList()).size()>5
)res.add(tar);
}
)
).get();
myPool.awaitTermination(3, TimeUnit.SECONDS);
myPool.shutdown();
修改結(jié)果
使用forkjoin指定線程數(shù)量,盡管CPU數(shù)量有限肝劲,依然獲得提升迁客。
多次測試郭宝,平均順序流耗時約34秒,并行流耗時約16秒哲泊。大概提升一倍的效率剩蟀。