首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

.NET4.0 并行循环效率对比测试,该怎么解决

2012-05-22 
.NET4.0 并行循环效率对比测试做了个.NET4.0 并行循环效率对比测试,发现并行效率居然比普通循环还要低。请

.NET4.0 并行循环效率对比测试
做了个.NET4.0 并行循环效率对比测试,发现并行效率居然比普通循环还要低。
请大家看看,是我代码问题还是微软忽悠人?

C# code
class Program    {        static void Main(string[] args)        {            Stopwatch timer1 = new Stopwatch();            Stopwatch timer2 = new Stopwatch();            timer1.Start();            int max=10000000;            ConcurrentQueue<int> intQueue = new ConcurrentQueue<int>();            ConcurrentQueue<int> intQueueParallel = new ConcurrentQueue<int>();            for (int i = 0; i < max; i++)            {                intQueue.Enqueue(i);            }                //List< int> intList=intQueue.ToList<int>();            timer1.Stop();            Console.WriteLine("普通循环共耗时:" + timer1.Elapsed.TotalSeconds + "秒");             timer2.Start();            Parallel.For(0, max, (i) => intQueueParallel.Enqueue(i));            //List<int> intListParallel = intQueueParallel.ToList<int>();            timer2.Stop();            Console.WriteLine("并行共耗时:"+timer2.Elapsed.TotalSeconds+"秒");            Console.ReadKey();        }    }


normal:1.22s
parallel:1.61s

[解决办法]
探讨

我重新做了个测试:
C# code
class Program
{
static void Main(string[] args)
{
Stopwatch timer1 = new Stopwatch();
Stopwatch timer2 = new Stopwatch();
……

[解决办法]
好歹看下MSDN再开始干啊

当 For() 循环的循环体很小时,它的执行速度可能比等效的顺序循环更慢。 对数据进行分区所涉及的开销以及调用每个循环迭代上的委托的开销导致了性能降低。 为了解决类似情况,Partitioner 类提供 Create 方法,该方法使您可以为委托体提供顺序循环,以便每个分区只调用一次委托,而不是每个迭代调用一次委托。 有关更多信息,请参见 PLINQ 和 TPL 的自定义分区程序。 

http://msdn.microsoft.com/zh-cn/library/dd560853.aspx

热点排行