首页 > 代码库 > C#并行计算一定能提高性能?
C#并行计算一定能提高性能?
#region 单层循环 public static void CompareSingleCycle() { var data = http://www.mamicode.com/Enumerable.Range(0, 100000000).ToArray();"NormalSingleCycle", () => NormalSingleCycle(data)); Timing("ParallelSingleCycle", () => ParallelSingleCycle(data)); } private static void NormalSingleCycle(int[] data) { for (int i = 0; i < data.Length; i++) { data[i]++; } } private static void ParallelSingleCycle(int[] data) { Parallel.For(0, data.Length, (i) => data[i]++); } #endregion #region 多层循环 public static void CompareMultiCycle() { var data = http://www.mamicode.com/Enumerable.Range(0, 100000000).ToArray();"NormalMultiCycle", () => NormalMultiCycle(data)); Timing("ParallelMultiCycle", () => ParallelMultiCycle(data)); } private static void NormalMultiCycle(int[] data) { for (int i = 0; i < data.Length; i++) { for (int j = 0; j < 5; j++) { for (int k = 0; k < 5; k++) { data[i] += j + k; } } } } private static void ParallelMultiCycle(int[] data) { Parallel.For(0, data.Length, (i) => { for (int j = 0; j < 5; j++) { for (int k = 0; k < 5; k++) { data[i] += j + k; } } }); } #endregion private static void Timing(string name, Action action) { Stopwatch sw = new Stopwatch(); sw.Start(); action(); sw.Stop(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("【 {0} 】: {1} ms", name, sw.ElapsedMilliseconds); Console.ResetColor(); }
实际与想象貌似还真的不一样。
C#并行计算一定能提高性能?
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。