c# 并行运算
1. Parallel.INVOKE() 看实例:
private static Stopwatch watch = new Stopwatch(); private static void Run1() { Thread.Sleep(2000); Console.WriteLine("Task 1 takes 2 sec"); } private static void Run2() { Thread.Sleep(3000); Console.WriteLine("Task 2 takes 3 sec"); } static void Main(string[] args) { watch.Start(); Parallel.Invoke(Run1,Run2); watch.Stop(); Console.WriteLine("Parallel run "+watch.ElapsedMilliseconds +" ms"); watch.Restart(); Run1(); Run2(); watch.Stop(); Console.WriteLine("Normal run "+watch.ElapsedMilliseconds+" ms"); Console.ReadLine();
看结果:
2.Parallel.For
看实例:
watch.Start(); for (int i = 0; i < 10000; i++) { for (int j = 0; j < 5000; j++) { int sum = 0; sum++; } } watch.Stop(); Console.WriteLine("Normal run " + watch.ElapsedMilliseconds + "ms"); watch.Restart(); watch.Start(); Parallel.For(0, 1000, item => { for (int j = 0; j < 5000; j++) { int sum = 0; sum += item; } }); watch.Stop(); Console.WriteLine("ParalleFor run " + watch.ElapsedMilliseconds + "ms"); Console.ReadLine();
看结果:
是不是Parallel.For在任何时候都比for要快呢?答案当然是“不是”,要不然微软还留着for干嘛?
看实例:
时间: 2024-10-04 17:02:50