0
我的理解是/:与foldLeft相同,并且聚合是foldLeft的更快版本,如果列表使用“par”转换为并行集合。如果我是正确的,为什么下面的代码显示:/和foldLeft比列表上使用'par'的集合更快。Scala - 聚合与性能的比较leftLeft
我正在计算一个大列表的元素总数和元素数量,并将结果存储在一个元组[Double,Double]中。
//initial tuple2 (sum,count)
val tsc:Tuple2[Double,Double] = Tuple2(0.0,0.0)
//create a large list
val largeList = List.tabulate(500000)(n=>n*n)
//note time
val time1 = System.currentTimeMillis
//using aggregate without par
largeList.aggregate(tsc) ((tsc,elem) => (tsc._1+elem, tsc._2+1), (tsc1, tsc2)=>((tsc1._1+tsc2._1), (tsc1._2+tsc2._2)))
//note time
val time2 = System.currentTimeMillis
//use aggregate with par
largeList.par.aggregate(tsc) ((tsc,elem) => (tsc._1+elem, tsc._2+1), (tsc1, tsc2)=>((tsc1._1+tsc2._1), (tsc1._2+tsc2._2)))
//note time
val time3 = System.currentTimeMillis
//use /:
(tsc /: largeList)((tsc,elem)=>(tsc._1+elem, tsc._2+1))
//note time
val time4 = System.currentTimeMillis
//use foldLeft
largeList.foldLeft(tsc)((tsc,elem)=>(tsc._1+elem, tsc._2+1))
//note time
val time5 = System.currentTimeMillis
//calcualte time difference
println ("Time without par (millisecond)"+(time2-time1))
println ("Time with par (millisecond)"+(time3-time2))
println ("Time with /: (millisecond)"+(time4-time3))
println ("Time with FoldLeft (millisecond)"+(time5-time4)
我得到了第一次运行结果如下
结果
Time without par (millisecond)1198
Time with par (millisecond)1479
Time with /: (millisecond)626
Time with FoldLeft (millisecond)661
结果在第二次运行
Time without par (millisecond)703
Time with par (millisecond)581
Time with /: (millisecond)435
Time with FoldLeft (millisecond)423
我使用CMD运行这个在Windows 10。 /:和FoldLeft在性能上看起来相似,并且比汇总好得多。在第一轮运行中,使用par进行汇总实际上更耗时。由于窗口中的'cmd'(控制台)无法利用多线程(这里只是猜测),这可能是一个问题吗?