Advertisement
Guest User

ConcurrentBag VS ConcurrentQueue - producers only

a guest
Nov 2nd, 2016
463
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.48 KB | None | 0 0
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using BenchmarkDotNet.Attributes;
  7. using BenchmarkDotNet.Configs;
  8. using BenchmarkDotNet.Diagnostics.Windows;
  9. using BenchmarkDotNet.Jobs;
  10. using BenchmarkDotNet.Running;
  11.  
  12. namespace ConsoleApplication27
  13. {
  14.     class Program
  15.     {
  16.         static void Main()
  17.         {
  18.             BenchmarkRunner.Run<Test>(ManualConfig
  19.             .Create(DefaultConfig.Instance)
  20.             .With(new MemoryDiagnoser()));
  21.  
  22.             Console.WriteLine(Test.MyCount);
  23.         }
  24.     }
  25.  
  26.     public class Test
  27.     {
  28.         public static int MyCount { get; private set; }
  29.  
  30.         [Benchmark]
  31.         public Task Bag()
  32.         {
  33.             var bag = new ConcurrentBag<int>();
  34.             return Run(bag, i => bag.Add(i));
  35.         }
  36.  
  37.         [Benchmark]
  38.         public Task Queue()
  39.         {
  40.             var queue = new ConcurrentQueue<int>();
  41.             return Run(queue, i => queue.Enqueue(i));
  42.         }
  43.  
  44.         private async Task Run(IEnumerable<int> c, Action<int> add)
  45.         {
  46.             await Task.WhenAll(Enumerable.Range(0, Environment.ProcessorCount).Select(x => Task.Run(() =>
  47.             {
  48.                 for (int i = 0; i < 100000; i++)
  49.                 {
  50.                     add(i);
  51.                 }
  52.             })));
  53.  
  54.             foreach (var i in c)
  55.             {
  56.                 MyCount++;
  57.             }
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement