我对PLINQ有一些奇怪的结果,我似乎无法解释。我一直在尝试并行化Alpha Beta树搜索以加快搜索过程,但它实际上正在减慢它的速度。我希望随着我提高并行度,我会每秒线性增加节点数......然后处理其他节点,因为修剪会被推迟到以后。虽然节点数与期望值匹配,但我的时间不会:
非PLINQ, 访问过的节点:61418, 运行时:0:00.67
并行度:1, 访问过的节点:61418, runtime:0:01.48
并行度:2, 访问过的节点:75504, runtime:0:10.08
并行度:4, 访问过的节点:95664, runtime:1:51.98并行度:8, 访问过的节点:108148, 运行时:1:48.94
有人帮我识别可能的罪魁祸首吗?
相关代码:
public int AlphaBeta(IPosition position, AlphaBetaCutoff parent, int depthleft)
{
if (parent.Cutoff)
return parent.Beta;
if (depthleft == 0)
return Quiesce(position, parent);
var moves = position.Mover.GetMoves().ToList();
if (!moves.Any(m => true))
return position.Scorer.Score();
//Young Brothers Wait Concept...
var first = ProcessScore(moves.First(), parent, depthleft);
if(first >= parent.Beta)
{
parent.Cutoff = true;
return parent.BestScore;
}
//Now parallelize the rest...
if (moves.Skip(1)
.AsParallel()
.WithDegreeOfParallelism(1)
.WithMergeOptions(ParallelMergeOptions.NotBuffered)
.Select(m => ProcessScore(m, parent, depthleft))
.Any(score => parent.BestScore >= parent.Beta))
{
parent.Cutoff = true;
return parent.BestScore;
}
return parent.BestScore;
}
private int ProcessScore(IMove move, AlphaBetaCutoff parent, int depthleft)
{
var child = ABFactory.Create(parent);
if (parent.Cutoff)
{
return parent.BestScore;
}
var score = -AlphaBeta(move.MakeMove(), child, depthleft - 1);
parent.Alpha = score;
parent.BestScore = score;
if (score >= parent.Beta)
{
parent.Cutoff = true;
}
return score;
}
然后是跨树级别共享Alpha Beta参数的数据结构...
public class AlphaBetaCutoff
{
public AlphaBetaCutoff Parent { get; set; }
private bool _cutoff;
public bool Cutoff
{
get
{
return _cutoff || (Parent != null && Parent.Cutoff);
}
set
{
_cutoff = value;
}
}
private readonly object _alphaLock = new object();
private int _alpha = -10000;
public int Alpha
{
get
{
if (Parent == null) return _alpha;
return Math.Max(-Parent.Beta, _alpha);
}
set
{
lock (_alphaLock)
{
_alpha = Math.Max(_alpha, value);
}
}
}
private int _beta = 10000;
public int Beta
{
get
{
if (Parent == null) return _beta;
return -Parent.Alpha;
}
set
{
_beta = value;
}
}
private readonly object _bestScoreLock = new object();
private int _bestScore = -10000;
public int BestScore
{
get
{
return _bestScore;
}
set
{
lock (_bestScoreLock)
{
_bestScore = Math.Max(_bestScore, value);
}
}
}
}
答案 0 :(得分:0)
当你只为很少的工作和为所有底层节点设置新线程时,你会在线程上产生巨大的开销。您可能因为Any而处理更多节点,通常处理会停止,但有些节点在找到Any(第一个匹配)之前已经开始处理。当您拥有一组已知的大型底层工作负载时,并行性将更好地发挥作用。如果您只在顶级节点执行并行操作,可以尝试会发生什么。