您的位置:首页 > 编程语言 > C#

C# 使用Parallel并行开发Parallel.For、Parallel.Foreach实例

2016-06-12 12:23 676 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace ConsoleApplication1
{
class Program
{
/*
* 测试分析结果
* Parallel.For、Parallel.Foreach发挥出了平行运算的优势,将效率提高了接近一半左右。
*
* 测试总结
* 对于Parallel.For、Parallel.Foreach的使用应该要特别小心,
* 它们的优势是处理列表很长,且对列表内的元素进行很复杂的业务逻辑,且不会使用共享资源,
* 只针对自身的业务逻辑处理,方才能提升效率。
* 因为如果逻辑过于简单的话,创建线程的花费将大于业务执行的花费,得不偿失。
*/
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;
ConcurrentStack<int> resultData = new ConcurrentStack<int>();
Parallel.ForEach(testData, (item, loopState) =>
{
item.ToString();
});
Console.WriteLine(string.Format("Parallel.ForEach:t{0} in {1}", testData.Sum(), (DateTime.Now - time1).TotalMilliseconds));
}
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: