1 #region Copyright notice and license 2 3 // Copyright 2015 gRPC authors. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 #endregion 18 19 using System; 20 using System.Runtime.InteropServices; 21 using System.Threading; 22 using Grpc.Core; 23 using Grpc.Core.Internal; 24 using System.Collections.Generic; 25 using System.Diagnostics; 26 27 namespace Grpc.Microbenchmarks 28 { 29 public class CompletionRegistryBenchmark 30 { 31 GrpcEnvironment environment; 32 Init()33 public void Init() 34 { 35 environment = GrpcEnvironment.AddRef(); 36 } 37 Cleanup()38 public void Cleanup() 39 { 40 GrpcEnvironment.ReleaseAsync().Wait(); 41 } 42 Run(int threadCount, int iterations, bool useSharedRegistry)43 public void Run(int threadCount, int iterations, bool useSharedRegistry) 44 { 45 Console.WriteLine(string.Format("CompletionRegistryBenchmark: threads={0}, iterations={1}, useSharedRegistry={2}", threadCount, iterations, useSharedRegistry)); 46 CompletionRegistry sharedRegistry = useSharedRegistry ? new CompletionRegistry(environment, () => BatchContextSafeHandle.Create(), () => RequestCallContextSafeHandle.Create()) : null; 47 var threadedBenchmark = new ThreadedBenchmark(threadCount, () => ThreadBody(iterations, sharedRegistry)); 48 threadedBenchmark.Run(); 49 // TODO: parametrize by number of pending completions 50 } 51 ThreadBody(int iterations, CompletionRegistry optionalSharedRegistry)52 private void ThreadBody(int iterations, CompletionRegistry optionalSharedRegistry) 53 { 54 var completionRegistry = optionalSharedRegistry ?? new CompletionRegistry(environment, () => throw new NotImplementedException(), () => throw new NotImplementedException()); 55 var ctx = BatchContextSafeHandle.Create(); 56 57 var stopwatch = Stopwatch.StartNew(); 58 for (int i = 0; i < iterations; i++) 59 { 60 completionRegistry.Register(ctx.Handle, ctx); 61 var callback = completionRegistry.Extract(ctx.Handle); 62 // NOTE: we are not calling the callback to avoid disposing ctx. 63 } 64 stopwatch.Stop(); 65 Console.WriteLine("Elapsed millis: " + stopwatch.ElapsedMilliseconds); 66 67 ctx.Recycle(); 68 } 69 70 private class NopCompletionCallback : IOpCompletionCallback 71 { OnComplete(bool success)72 public void OnComplete(bool success) 73 { 74 75 } 76 } 77 } 78 } 79