|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Threading; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using BenchmarkDotNet.Attributes; |
| 7 | + |
| 8 | +namespace Microsoft.Extensions.ObjectPool.Microbenchmarks; |
| 9 | + |
| 10 | +[MemoryDiagnoser] |
| 11 | +public class DrainRefillMultiTheaded |
| 12 | +{ |
| 13 | + private DefaultObjectPool<Foo> _pool = null!; |
| 14 | + private Foo[][] _stores = null!; |
| 15 | + private ManualResetEventSlim _terminate = null!; |
| 16 | + private Task[] _tasks = null!; |
| 17 | + |
| 18 | + [Params(8, 16, 64, 256, 1024, 2048)] |
| 19 | + public int Count { get; set; } |
| 20 | + |
| 21 | + [Params(1, 2, 4, 8)] |
| 22 | + public int ThreadCount { get; set; } |
| 23 | + |
| 24 | + [GlobalSetup] |
| 25 | + public void GlobalSetup() |
| 26 | + { |
| 27 | + _pool = new DefaultObjectPool<Foo>(new DefaultPooledObjectPolicy<Foo>(), Count); |
| 28 | + for (int i = 0; i < Count; i++) |
| 29 | + { |
| 30 | + _pool.Return(new Foo()); |
| 31 | + } |
| 32 | + |
| 33 | + _stores = new Foo[ThreadCount][]; |
| 34 | + for (int i = 0; i < ThreadCount; i++) |
| 35 | + { |
| 36 | + _stores[i] = new Foo[Count]; |
| 37 | + } |
| 38 | + |
| 39 | + _terminate = new ManualResetEventSlim(); |
| 40 | + |
| 41 | + _tasks = new Task[ThreadCount - 1]; |
| 42 | + for (int i = 0; i < ThreadCount - 1; i++) |
| 43 | + { |
| 44 | + int threadIndex = i; |
| 45 | + _tasks[i] = Task.Run(() => |
| 46 | + { |
| 47 | + while (!_terminate.IsSet) |
| 48 | + { |
| 49 | + BenchmarkLoop(_stores[threadIndex]); |
| 50 | + } |
| 51 | + }); |
| 52 | + } |
| 53 | + |
| 54 | + // give ample time to the contention tasks to start running |
| 55 | + Thread.Sleep(250); |
| 56 | + } |
| 57 | + |
| 58 | + [GlobalCleanup] |
| 59 | + public void GlobalCleanup() |
| 60 | + { |
| 61 | + _terminate.Set(); |
| 62 | + Task.WaitAll(_tasks); |
| 63 | + _terminate.Dispose(); |
| 64 | + } |
| 65 | + |
| 66 | + [Benchmark] |
| 67 | + public void DrainRefillMulti() |
| 68 | + { |
| 69 | + BenchmarkLoop(_stores[ThreadCount - 1]); // take the last slot |
| 70 | + } |
| 71 | + |
| 72 | + private void BenchmarkLoop(Foo[] store) |
| 73 | + { |
| 74 | + int num = (Count / ThreadCount) - 1; |
| 75 | + |
| 76 | + for (int i = 0; i < num; i++) |
| 77 | + { |
| 78 | + store[i] = _pool.Get(); |
| 79 | + store[i].SimulateWork(); |
| 80 | + } |
| 81 | + |
| 82 | + for (int i = 0; i < num; i++) |
| 83 | + { |
| 84 | + store[i].SimulateWork(); |
| 85 | + _pool.Return(store[i]); |
| 86 | + } |
| 87 | + } |
| 88 | +} |
0 commit comments