我比较两种广度优先搜索算法的时间执行差异。平行和非平行。但是对于我制作的每个图表而言,非并行版本比并行版本快10倍。并行广度优先搜索
这是平行的广度优先搜索。我不知道问题出在哪里,但我在此方法中假设的地方:
public static int PBFS(Node start, Node end)
{
var queue = new ConcurrentQueue<Node>();
queue.Enqueue(start);
while (queue.Count != 0)
{
bool isFinished = false;
if (isFinished) break;
Parallel.ForEach<Node>(queue, CurrentNode =>
{
if (queue.TryDequeue(out CurrentNode))
{
foreach (Node Child in CurrentNode.Children.Keys)
{
if (Child.IsVisited == false)
{
Child.IsVisited = true;
if (Child == end) { isFinished = true; return; }
}
queue.Enqueue(Child);
}
}
return;
});
} return 1;
}
这是不平行的BFS:
public static int BFS(Node start, Node end)
{
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(start);
while (queue.Count != 0)
{
Node CurrentNode = queue.Dequeue();
CurrentNode.IsVisited = true;
foreach (Node Child in CurrentNode.Children.Keys)
{
if (Child.IsVisited == false)
{
Child.IsVisited = true;
//Console.Write(Child.Name+" ");
if (Child == end) return 1;
}
queue.Enqueue(Child);
}
// Console.WriteLine();
}
// Console.WriteLine();
return 0;
}
我知道这不是你要求的,但你的并行代码总是返回1.我建议将'isFinished'的声明移到while循环之外,并将它调用为'found'。然后,在你的函数结束时,如果'found'返回1,否则返回0。 –
返回只是因为函数是int。并不意味着什么 – bljuvko
您可以通过在'while循环的每次迭代开始时创建一个新临时'ConcurrentQueue'来移除少量争用,将子队列入队列,然后使'queue'引用您的(现在是完整的)临时队列,在'while循环的每次迭代结束时。 –