Parallel Power并行的力量(一个测试代码)

Parallel
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7.  
  8. namespace ConsoleApplication2
  9. {
  10.     class Test
  11.     {
  12.         static void Main()
  13.         {
  14.             int max = 500;
  15.             var query = Enumerable.Range(0, max)
  16.                                   .Select(SlowProjection)
  17.                                   .Where(x => x > 10)
  18.                                   .AsParallel();
  19.             Stopwatch sw = Stopwatch.StartNew();
  20.             int count = query.Count();
  21.             sw.Stop();
  22.             Console.WriteLine("Count: {0} in {1}ms", count,
  23.                               sw.ElapsedMilliseconds);
  24.  
  25.             query = Enumerable.Range(0, max)
  26.                               .AsParallel()
  27.                               .Select(SlowProjection)
  28.                               .Where(x => x > 10);
  29.             sw = Stopwatch.StartNew();
  30.             count = query.Count();
  31.             sw.Stop();
  32.             Console.WriteLine("Count: {0} in {1}ms", count,
  33.                               sw.ElapsedMilliseconds);
  34.             Console.Read();
  35.         }
  36.  
  37.         static int SlowProjection(int input)
  38.         {
  39.             Thread.Sleep(100);
  40.             return input;
  41.         }
  42.     }
  43.  
  44. }

这里比较了两种使用并行效率的比较,没有写顺序执行的原因你懂的.

posted @   today4king  阅读(307)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示
主题色彩