Parallel.ForEach() 並行循環


現在的電腦幾乎都是多核的,但在軟件中並還沒有跟上這個節奏,大多數軟件還是采用傳統的方式,並沒有很好的發揮多核的優勢。
微軟的並行運算平台(Microsoft’s Parallel Computing Platform (PCP))提供了這樣一個工具,讓軟件開發人員可以有效的使用多核提供的性能。
Parallel.ForEach()和Parallel.For()就是微軟並發類的成員。
今天做了一個簡單的測試,我的電腦是雙核的,效果還是比較明顯的。
一般的for和foreach循環用時都在10秒鍾;並發for循環在0.5秒,並發foreach在0.1秒鍾。
但是並發循環不能濫用,在簡單的少次數循環下,並發循環可能會體現不出其優勢。
下面是簡單的測試代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace parallelForeach
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime startTime;
            TimeSpan resultTime;
            List<entityA> source = new List<entityA>();
            for (int i = 0; i < 100; i++)
            {
                source.Add(new entityA
                {
                    name = "悟空" + i,
                    sex = i % 2 == 0 ? "" : "",
                    age = i
                });
            }
            startTime = System.DateTime.Now;
            loop1(source);
            resultTime = System.DateTime.Now - startTime;
            Console.WriteLine("一般for循環耗時:" + resultTime);
            startTime = System.DateTime.Now;
            loop2(source);
            resultTime = System.DateTime.Now - startTime;
            Console.WriteLine("一般foreach循環耗時:" + resultTime);
            startTime = System.DateTime.Now;
            loop3(source);
            resultTime = System.DateTime.Now - startTime;
            Console.WriteLine("並行for循環耗時:" + resultTime.Milliseconds);
            startTime = System.DateTime.Now;
            loop4(source);
            resultTime = System.DateTime.Now - startTime;
            Console.WriteLine("並行foreach循環耗時:" + resultTime.Milliseconds);
            Console.ReadLine();
        }

//普通的for循環
        static void loop1(List<entityA> source)
        {
            int count = source.Count();
            for (int i = 0; i < count; i++)
            {
                System.Threading.Thread.Sleep(100);
            }
        }

//普通的foreach循環
        static void loop2(List<entityA> source)
        {
            foreach (entityA item in source)
            {
                System.Threading.Thread.Sleep(100);
            }
        }

//並行的for循環
        static void loop3(List<entityA> source)
        {
            int count = source.Count();
            Parallel.For(0, count, item =>
            {
                System.Threading.Thread.Sleep(100);
            });
        }

//並行的foreach循環
        static void loop4(List<entityA> source)
        {
            Parallel.ForEach(source, item =>
            {
                System.Threading.Thread.Sleep(100);
            });
        }
    }

//簡單的實體
    class entityA
    {
        public string name { set; get; }
        public string sex { set; get; }
        public int age { set; get; }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM