結果が何であるかに応じて、返された結果セットを特定の方法で色分けするプログラムがあります。結果を色分けするのに時間がかかるため (現在は Regex と RichTextBox.Select + .SelectionColor で行っています)、400 件の結果で色分けを切り捨てました。その数のあたりで、約 20 秒かかります。これは、私が妥当と考える最大時間です。
Parallel.ForEach
パフォーマンスの向上を試みるために、ループを使用して を反復処理するように Regex 部分を書き直しましMatchCollection
たが、時間はほぼ同じでした (18 ~ 19 秒対 20 秒)。並列プログラミングに非常に適した仕事ではありませんか? 何か違うことを試す必要がありますか?どんなアドバイスでも大歓迎です。ありがとう!
PS: Parallel.ForEach の有無にかかわらず、私の CPU 使用率が約 14% にならないのは少し奇妙だと思いました。
コード
MatchCollection startMatches = Regex.Matches(tempRTB.Text, startPattern);
object locker = new object();
System.Threading.Tasks.Parallel.ForEach(startMatches.Cast<Match>(), m =>
{
int i = 0;
foreach (Group g in m.Groups)
{
if (i > 0 && i < 5 && g.Length > 0)
{
tempRTB.Invoke(new Func<bool>(
delegate
{
lock (locker)
{
tempRTB.Select(g.Index, g.Length);
if ((i & 1) == 0) // Even number
tempRTB.SelectionColor = Namespace.Properties.Settings.Default.ValueColor;
else // Odd number
tempRTB.SelectionColor = Namespace.Properties.Settings.Default.AttributeColor;
return true;
}
}));
}
else if (i == 5 && g.Length > 0)
{
var result = tempRTB.Invoke(new Func<string>(
delegate
{
lock (locker)
{
return tempRTB.Text.Substring(g.Index, g.Length);
}
}));
MatchCollection subMatches = Regex.Matches((string)result, pattern);
foreach (Match subMatch in subMatches)
{
int j = 0;
foreach (Group subGroup in subMatch.Groups)
{
if (j > 0 && subGroup.Length > 0)
{
tempRTB.Invoke(new Func<bool>(
delegate
{
lock (locker)
{
tempRTB.Select(g.Index + subGroup.Index, subGroup.Length);
if ((j & 1) == 0) // Even number
tempRTB.SelectionColor = Namespace.Properties.Settings.Default.ValueColor;
else // Odd number
tempRTB.SelectionColor = Namespace.Properties.Settings.Default.AttributeColor;
return true;
}
}));
}
j++;
}
}
}
i++;
}
});