c# Parallel.ForEach和for性能对比

今天百忙之中,突发奇想,证明一下Parallel.ForEach和for性能,

namespace ParallelTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ConcurrentBag listStatus = new ConcurrentBag();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Parallel.For(0, 1000, (i) =>
              {
                  listStatus.Add(i);
                  Thread.Sleep(100);
              });
            sw.Stop();
            label_Parallel.Text = string.Format("Parallel 耗时:{0}", sw.ElapsedMilliseconds);
            sw.Reset();
            listStatus = new ConcurrentBag();
            sw.Start();
            for(int i=0;i<1000;i++)
            {
                listStatus.Add(i);
                Thread.Sleep(100);
            }
            sw.Stop();
            label_For.Text = string.Format("for 耗时:{0}", sw.ElapsedMilliseconds);
        }
    }
}

 

c# Parallel.ForEach和for性能对比_第1张图片

如果去掉Sleep语句。

代码如下:

namespace ParallelTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ConcurrentBag listStatus = new ConcurrentBag();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Parallel.For(0, 1000, (i) =>
              {
                  listStatus.Add(i);
                  //Thread.Sleep(100);
              });
            sw.Stop();
            label_Parallel.Text = string.Format("Parallel 耗时:{0}", sw.ElapsedMilliseconds);
            sw.Reset();
            listStatus = new ConcurrentBag();
            sw.Start();
            for(int i=0;i<1000;i++)
            {
                listStatus.Add(i);
                //Thread.Sleep(100);
            }
            sw.Stop();
            label_For.Text = string.Format("for 耗时:{0}", sw.ElapsedMilliseconds);
        }
    }

c# Parallel.ForEach和for性能对比_第2张图片

结论:

Parallel在循环中的每个任务很简单,耗时很小时,并不具备优势,反而因为多线程开销导致效率低下。

但在每个任务耗时较大时,应该使用Parallel,实现并发

你可能感兴趣的:(c#)