C# Parallel 并行计算测试


	    ConcurrentBag<int> list1 = new ConcurrentBag<int>();           
            Stopwatch stop1 = new Stopwatch();
            stop1.Start();
            Parallel.For(0, 10000, item =>
            {
                Thread.Sleep(1);
                list1.Add(item);
            });
            stop1.Stop();
            AppendLine("Count1:" + list1.Count() + " " + stop1.ElapsedMilliseconds);

            List<int> list2 = new List<int>();
            object synObj = new object();
            Stopwatch stop2 = new Stopwatch();
            stop2.Start();
            //DateTime be = DateTime.Now;
            Parallel.For(0, 10000, item =>
            {
                lock (synObj)
                {
                    Thread.Sleep(1);
                    list2.Add(item);
                }
            });
           // DateTime en = DateTime.Now;
            stop2.Stop();
            AppendLine("Count2:" + list2.Count() + " " + stop2.ElapsedMilliseconds );

            List<int> list3 = new List<int>();           
            Stopwatch stop3 = new Stopwatch();
            stop3.Start();
            for(var item = 0;item<10000;item++)
            {
                Thread.Sleep(1);
               list3.Add(item);                
            }
            stop3.Stop();
            AppendLine("Count3:" + list3.Count() + " " + stop3.ElapsedMilliseconds);

三次运行结果:

2017-05-25 17:06:42 Count1:10000 2856
2017-05-25 17:06:52 Count2:10000 10184
2017-05-25 17:07:02 Count3:10000 10043

2017-05-25 17:07:13 Count1:10000 1420
2017-05-25 17:07:23 Count2:10000 10075
2017-05-25 17:07:33 Count3:10000 9999

2017-05-25 17:15:27 Count1:10000 672
2017-05-25 17:15:37 Count2:10000 10456
2017-05-25 17:15:47 Count3:10000 10017


都不加sleep运行结果:

2017-05-25 17:17:28 Count1:10000 2
2017-05-25 17:17:28 Count2:10000 1
2017-05-25 17:17:28 Count3:10000 0

2017-05-25 17:17:29 Count1:10000 20
2017-05-25 17:17:29 Count2:10000 0
2017-05-25 17:17:29 Count3:10000 3

2017-05-25 17:17:30 Count1:10000 1
2017-05-25 17:17:30 Count2:10000 4
2017-05-25 17:17:30 Count3:10000 0

测试结果看出,不加sleep串行更快,加sleep并行更快,如果正式环境肯定会有比sleep(1)更长的延时,所以对于add操作并行还是有优势的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值