本文主要是介绍C#【多线程篇】Parallel.For和for的效率比较(Paralle.Foreach和foreach比较类似),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、执行耗时任务(Parallel.For更快,多线程执行)
using System;
using System.Threading.Tasks; // Must use this namespace
using System.Diagnostics;
using System.Threading;namespace ExampleParallelFor
{class Program{static void Main(){const int maxValues = 100;//forint[] squares = new int[maxValues];Stopwatch sw = new Stopwatch();sw.Start();for (int i = 0; i < maxValues; i++){squares[i] = i * i;Thread.Sleep(10);}Console.WriteLine("for time:{0}", sw.ElapsedMilliseconds.ToString());//Parallel.Forint[] squares1 = new int[maxValues];Stopwatch sw1= new Stopwatch();sw1.Start(); Parallel.For(0, maxValues, i => { squares[i] = i * i; Thread.Sleep(10); });Console.WriteLine("Paralle.For time:{0}", sw1.ElapsedMilliseconds.ToString());//for (int i = 0; i < maxValues; i++)//{ Console.WriteLine("Element {0}: {1}", i, squares[i]); }Console.ReadLine();}}
}
执行结果:
2、执行短小(时间短、耗时小)任务(for更快,单线程执行)
using System;
using System.Threading.Tasks; // Must use this namespace
using System.Diagnostics;
using System.Threading;namespace ExampleParallelFor
{class Program{static void Main(){const int maxValues = 100;//forint[] squares = new int[maxValues];Stopwatch sw = new Stopwatch();sw.Start();for (int i = 0; i < maxValues; i++){squares[i] = i * i;//Thread.Sleep(10);}Console.WriteLine("for time:{0}", sw.ElapsedMilliseconds.ToString());//Parallel.Forint[] squares1 = new int[maxValues];Stopwatch sw1= new Stopwatch();sw1.Start(); Parallel.For(0, maxValues, i => { squares[i] = i * i;/* Thread.Sleep(10);*/ });Console.WriteLine("Paralle.For time:{0}", sw1.ElapsedMilliseconds.ToString());//for (int i = 0; i < maxValues; i++)//{ Console.WriteLine("Element {0}: {1}", i, squares[i]); }Console.ReadLine();}}
}
执行结果:
这篇关于C#【多线程篇】Parallel.For和for的效率比较(Paralle.Foreach和foreach比较类似)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!