c# 并行计算(大量循环处理的场景下)

介绍

并行指有多个CPU资源同时处理多个线程,不存在竞争的概念,可以大量节省运行时间。

用法参考

微软官方用法

编码

using System;
using System.Collections.Generic;

namespace ParallelTest
{
    
    
    public class TestObj
    {
    
    
        public List<double> RandomList = new List<double>();

        public void InitValue()
        {
    
    
            Random random = new Random((int)DateTime.Now.ToOADate());
            for (int i = 0; i < 10e6; i++)//1亿数值
            {
    
    
                RandomList.Add(random.NextDouble());
            }
            return;
        }

        public double Sum()
        {
    
    
            double refVel = 0;
            foreach (var item in RandomList)
            {
    
    
                refVel += item;
            }
            return refVel;
        }
    }
}

using ParallelTest;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    
    
    class Program
    {
    
    

        static void Main(string[] args)
        {
    
    
            List<TestObj> testObjs = new List<TestObj>();
            for (int i = 0; i < 100; i++)
            {
    
    
                testObjs.Add(new TestObj());
            }
            //foreach (var item in testObjs)
            //{
    
    
            //    item.InitValue();
            //}

            ParallelLoopResult result = Parallel.ForEach(testObjs, item =>
           {
    
    
               item.InitValue();
           });
            while (!result.IsCompleted)
            {
    
    
                Thread.Sleep(0);
            }
        }
    }


}


简单测试

单线程10亿数据随机数生成19.65s在这里插入图片描述

在这里插入图片描述

并行10亿随机数时间7.637s

在这里插入图片描述
在这里插入图片描述

结论

并行硬件资源利用更重复,省时省力,能用并行用并行

勘误

Parallel中方法为阻塞方法,无需通过ParallelLoopResult->IsCompleted()判断

猜你喜欢

转载自blog.csdn.net/bayinglong/article/details/130747098