我正忙于运行并行线程,因此我决定在较小的基础上对其进行测试,然后在我感到舒服时进行扩展。我将同样的过程与自己相提并论;一个使用 Parallel.For,另一个使用基本的 for 循环。我正在捕捉时间(以刻度为单位)进行比较。示例代码采用一个数组(在本例中为 53 个两个字符串)并ListBox
用数组填充给定的值。
对我来说几乎没有意义的是,当我运行基本的 For 循环时,它平均产生 1,400 个滴答声,但是当我运行Parallel.For
循环时,它平均返回 5,200 个滴答声。样本量是否太小而无法并行有效?
这是我正在使用的两个片段。Parallel.For
循环是:
public void ListboxFromArray(ListBox listbox, string[] array1)
{
// This method takes an array and fills a listbox full of items from the array
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Parallel.For(0, array1.Count(),
index =>
{
listbox.Items.Add(array1[index]);
});
stopWatch.Stop();
long ts = stopWatch.ElapsedTicks;
string elapsedTime = ts.ToString() + " Ticks"; ;
MessageBox.Show(elapsedTime);
}
for
循环是:
public void ListboxFromArray(ListBox listbox, string[] array1)
{
// This method takes an array and fills a listbox full of items from the array
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < array1.Count(); i++)
{
listbox.Items.Add(array1[i]);
}
stopWatch.Stop();
long ts = stopWatch.ElapsedTicks;
string elapsedTime = ts.ToString() + " Ticks"; ;
MessageBox.Show(elapsedTime);
}
感谢您提前输入或验证我的想法。