我有一個程序,它根據結果是以某種方式對返回的結果集進行顏色編碼。由於對結果進行顏色編碼需要很長時間(目前正在使用Regex和RichTextBox.Select + .SelectionColor完成),所以我在400個結果處切斷了顏色編碼。在這個數字大約需要20秒,這是我認爲合理的最大時間。Parallel.ForEach和Regex沒有性能提升嗎?
爲了提高性能,我重新編寫了正則表達式部分,使用Parallel.ForEach
循環遍歷MatchCollection
,但時間大約相同(18-19秒vs 20)!僅僅是不適合並行編程的工作呢?我應該嘗試不同的東西嗎?任何建議是受歡迎的。謝謝!
PS:以爲有點奇怪我的CPU利用率從來沒有下降到14%左右,無論有無Parallel.ForEach。
代碼
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++;
}
});
14%的利用率聽起來像是使用超線程技術的四核內核的一個內核的100%利用率。 – 2013-05-14 14:33:24
你機器上有多少核心? – LukeHennerley 2013-05-14 14:33:30
@LukeHennerley任務管理器顯示8(它是Intel i7-3770) – Hershizer33 2013-05-14 14:35:04