今天去微软文档里随便点了点,偶然看到Linq的介绍,虽然之前在项目中用过很多次,但是其实相关文档却看的甚少,理解可能就有些遗漏或者不正确,打算这几天盯着研究一把。
偶然看到一点PLinq示例,如下。对于AsParallel方法不是太懂,百度一把Parallel是并行的意思,估计是并行编程相关的吧,刚好看到微软给的图(如下),立马清晰许多。
1 public static string GetAllFacebookUserLikesMessage(IEnumerable<FacebookUser> facebookUsers) 2 { 3 var seed = default(UInt64); 4 5 Func<UInt64, UInt64, UInt64> threadAccumulator = (t1, t2) => t1 + t2; 6 Func<UInt64, UInt64, UInt64> threadResultAccumulator = (t1, t2) => t1 + t2; 7 Func<Uint64, string> resultSelector = total => $"Facebook has {total} likes!"; 8 9 return facebookUsers.AsParallel() 10 .Aggregate(seed, threadAccumulator, threadResultAccumulator, resultSelector); 11 }
我想并行的话应该比直接跑应该快一些吧,于是动手写了个例子。
1 static List<int> list = new List<int>(); 2 static void Main(string[] args) 3 { 4 var i = 0; 5 while (i < 10000) 6 { 7 i++; 8 list.Add(i); 9 } 10 11 TimeWatchHelper.Run(RunWithoutParallel); 12 TimeWatchHelper.Run(RunWithParallel); 13 } 14 15 static void RunWithoutParallel() 16 { 17 int seed = 5; 18 list.Aggregate(seed, (s1, s2) => s1 + s2); 19 } 20 21 static void RunWithParallel() 22 { 23 int seed = 5; 24 list.AsParallel().Aggregate(seed, (s1, s2) => s1 + s2, (s1, s2) => s1 + s2, s1 => s1); 25 }
得出结果如下。
TimeWatchHelper里面每个方法会跑10000次,然后记下时间,非并行跑了802ms,并行跑了320ms。
Over~
原文:https://www.cnblogs.com/xiaopcheche/p/10872780.html