首页 > 代码库 > c# 并行运算
c# 并行运算
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干嘛?
看实例:
c# 并行运算
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。