• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #region Copyright notice and license
2 
3 // Copyright 2019 The 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.Collections.Generic;
21 using BenchmarkDotNet.Attributes;
22 using Grpc.Core;
23 using Grpc.Core.Internal;
24 
25 namespace Grpc.Microbenchmarks
26 {
27     [ClrJob, CoreJob] // test .NET Core and .NET Framework
28     [MemoryDiagnoser] // allocations
29     public class Utf8Encode : ISendStatusFromServerCompletionCallback
30     {
31         [Params(0, 1, 4, 128, 1024)]
32         public int PayloadSize
33         {
34             get { return payloadSize; }
35             set
36             {
37                 payloadSize = value;
38                 status = new Status(StatusCode.OK, Invent(value));
39             }
40         }
41 
42         private int payloadSize;
43         private Status status;
44 
Invent(int length)45         static string Invent(int length)
46         {
47             var rand = new Random(Seed: length);
48             var chars = new char[length];
49             for(int i = 0; i < chars.Length; i++)
50             {
51                 chars[i] = (char)rand.Next(32, 300);
52             }
53             return new string(chars);
54         }
55 
56         private GrpcEnvironment environment;
57         private CompletionRegistry completionRegistry;
58         [GlobalSetup]
Setup()59         public void Setup()
60         {
61             var native = NativeMethods.Get();
62 
63             // nop the native-call via reflection
64             NativeMethods.Delegates.grpcsharp_call_send_status_from_server_delegate nop = (CallSafeHandle call, BatchContextSafeHandle ctx, StatusCode statusCode, IntPtr statusMessage, UIntPtr statusMessageLen, MetadataArraySafeHandle metadataArray, int sendEmptyInitialMetadata, SliceBufferSafeHandle optionalSendBuffer, WriteFlags writeFlags) => {
65                 completionRegistry.Extract(ctx.Handle).OnComplete(true); // drain the dictionary as we go
66                 return CallError.OK;
67             };
68             native.GetType().GetField(nameof(native.grpcsharp_call_send_status_from_server)).SetValue(native, nop);
69 
70             environment = GrpcEnvironment.AddRef();
71             metadata = MetadataArraySafeHandle.Create(Metadata.Empty);
72             completionRegistry = new CompletionRegistry(environment, () => environment.BatchContextPool.Lease(), () => throw new NotImplementedException());
73             var cq = CompletionQueueSafeHandle.CreateAsync(completionRegistry);
74             call = CreateFakeCall(cq);
75         }
76 
CreateFakeCall(CompletionQueueSafeHandle cq)77         private static CallSafeHandle CreateFakeCall(CompletionQueueSafeHandle cq)
78         {
79             var call = CallSafeHandle.CreateFake(new IntPtr(0xdead), cq);
80             bool success = false;
81             while (!success)
82             {
83                 // avoid calling destroy on a nonexistent grpc_call pointer
84                 call.DangerousAddRef(ref success);
85             }
86             return call;
87         }
88 
89         [GlobalCleanup]
Cleanup()90         public void Cleanup()
91         {
92             try
93             {
94                 metadata?.Dispose();
95                 metadata = null;
96                 call?.Dispose();
97                 call = null;
98 
99                 if (environment != null)
100                 {
101                     environment = null;
102                     // cleanup seems... unreliable on CLR
103                     // GrpcEnvironment.ReleaseAsync().Wait(1000);
104                 }
105             }
106             catch (Exception ex)
107             {
108                 Console.Error.WriteLine(ex.Message);
109             }
110         }
111         private CallSafeHandle call;
112         private MetadataArraySafeHandle metadata;
113 
114         const int Iterations = 1000;
115         [Benchmark(OperationsPerInvoke = Iterations)]
SendStatus()116         public unsafe void SendStatus()
117         {
118             for (int i = 0; i < Iterations; i++)
119             {
120                 call.StartSendStatusFromServer(this, status, metadata, false, SliceBufferSafeHandle.NullInstance, WriteFlags.NoCompress);
121             }
122         }
123 
ISendStatusFromServerCompletionCallback.OnSendStatusFromServerCompletion(bool success)124         void ISendStatusFromServerCompletionCallback.OnSendStatusFromServerCompletion(bool success) { }
125     }
126 }
127