【发布时间】:2012-03-16 18:53:08
【问题描述】:
所以我一直在 Scala 中为我正在处理的图形项目使用并行集合,我已经定义了图形类的基础知识,它目前使用的是 scala.collection.mutable.HashMap,其中键是 @987654324 @ 并且值为ListBuffer[Int](邻接列表)。 (编辑:此后已更改为ArrayBuffer[Int]
几个月前我在 C++ 中做过类似的事情,std::vector<int, std::vector<int> >。
我现在要做的是在图中的所有顶点对之间运行一个度量,所以在 C++ 中我做了这样的事情:
// myVec = std::vector<int> of vertices
for (std::vector<int>::iterator iter = myVec.begin(); iter != myVec.end(); ++iter) {
for (std::vector<int>::iterator iter2 = myVec.begin();
iter2 != myVec.end(); ++iter2) {
/* Run algorithm between *iter and *iter2 */
}
}
我在 Scala 中做了同样的事情,并行化,(或试图)这样做:
// vertexList is a List[Int] (NOW CHANGED TO Array[Int] - see below)
vertexList.par.foreach(u =>
vertexList.foreach(v =>
/* Run algorithm between u and v */
)
)
C++ 版本显然是单线程的,Scala 版本有.par,所以它使用并行集合并且在 8 核(同一台机器)上是多线程的。然而,C++ 版本在大约 3 天内处理了 305,570 对,而 Scala 版本迄今为止仅在 17 小时内处理了 23,573 对。
假设我的math 正确,单线程 C++ 版本比 Scala 版本快大约 3 倍。 Scala 真的比 C++ 慢得多,还是我完全误用了 Scala(我最近才开始使用 Scala 编程大约有 300 页)?
谢谢! -kstruct
编辑要使用 while 循环,我会做类似的事情吗..
// Where vertexList is an Array[Int]
vertexList.par.foreach(u =>
while (i <- 0 until vertexList.length) {
/* Run algorithm between u and vertexList(i) */
}
}
如果你们的意思是对整个事情使用 while 循环,是否有相当于 .par.foreach 的 while?
EDIT2 等一下,那个代码甚至都不对——我的错。我将如何使用 while 循环并行化它?如果我有一些 var i 来跟踪迭代,那么不是所有线程都共享 i 吗?
【问题讨论】:
-
这对我来说似乎太慢了。但是,如果没有更多信息,很难知道。内循环平均需要多长时间才能完成?我会尝试使用 YourKit 分析 scala 应用程序(单线程),以查看您的算法中的某些内容是否花费了令人惊讶的时间。
-
尝试分析它。我猜是因为拳击。
ListBuffer[Int]只能存储装箱的整数。尝试切换到Array[Int]。 -
它需要是一个 ArrayBuffer[Int] 对,因为用户可能决定添加/删除边缘?
-
见@higherkindeds preso docs.google.com/present/view?id=ddmmbr8g_11fp6dq96s
-
好读.. 但是,我将如何并行化
while循环?
标签: scala graph scala-collections parallel-collections