For、Foreach、和Parallel.For等简单的速度检测

控制台代码  直接复制即可

static void Main(string[] args)
        {

                List<int> testData = new List<int>();
                Random Rand = new Random();
                
                for (int i = 0; i < 1000000; i++)
                {
                    testData.Add(Rand.Next(1000));
                }
           
           
                Console.WriteLine(testData.Sum());

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine();
                TestFor(testData);
                TestParallelFor(testData);
                TestParallelForeach(testData);
            }
            Console.ReadKey();
            
        }

        static void TestFor(List<int> testData)
        {
            DateTime time1 = DateTime.Now;
            foreach (var item in testData)
            {
                item.ToString();
            }
            Console.WriteLine(string.Format("ForEach:     t{0} in {1}", testData.Sum(), (DateTime.Now - time1).TotalMilliseconds));
        }

        static void TestParallelFor(List<int> testData)
        {
            DateTime time1 = DateTime.Now;
            Parallel.For(0, testData.Count, (i, loopState) =>
            {
                testData[i].ToString();
            });
            Console.WriteLine(string.Format("Parallel.For:   t{0} in {1}", testData.Sum(), (DateTime.Now - time1).TotalMilliseconds));
        }

        static void TestParallelForeach(List<int> testData)
        {
            
            DateTime time1 = DateTime.Now;
            Parallel.ForEach(testData, (item, loopState) =>
            {
                item.ToString();
            });
            Console.WriteLine(string.Format("Parallel.ForEach:t{0} in {1}", testData.Sum(), (DateTime.Now - time1).TotalMilliseconds));
        }

 

posted on 2019-01-28 17:21  FFFYYY  阅读(142)  评论(0编辑  收藏  举报