Utf8Encode.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #region Copyright notice and license
  2. // Copyright 2019 The gRPC Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Collections.Generic;
  18. using BenchmarkDotNet.Attributes;
  19. using Grpc.Core;
  20. using Grpc.Core.Internal;
  21. namespace Grpc.Microbenchmarks
  22. {
  23. [ClrJob, CoreJob] // test .NET Core and .NET Framework
  24. [MemoryDiagnoser] // allocations
  25. public class Utf8Encode : ISendStatusFromServerCompletionCallback
  26. {
  27. [Params(0, 1, 4, 128, 1024)]
  28. public int PayloadSize
  29. {
  30. get { return payloadSize; }
  31. set
  32. {
  33. payloadSize = value;
  34. status = new Status(StatusCode.OK, Invent(value));
  35. }
  36. }
  37. private int payloadSize;
  38. private Status status;
  39. static string Invent(int length)
  40. {
  41. var rand = new Random(Seed: length);
  42. var chars = new char[length];
  43. for(int i = 0; i < chars.Length; i++)
  44. {
  45. chars[i] = (char)rand.Next(32, 300);
  46. }
  47. return new string(chars);
  48. }
  49. private GrpcEnvironment environment;
  50. private CompletionRegistry completionRegistry;
  51. [GlobalSetup]
  52. public void Setup()
  53. {
  54. var native = NativeMethods.Get();
  55. // nop the native-call via reflection
  56. 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) => {
  57. completionRegistry.Extract(ctx.Handle).OnComplete(true); // drain the dictionary as we go
  58. return CallError.OK;
  59. };
  60. native.GetType().GetField(nameof(native.grpcsharp_call_send_status_from_server)).SetValue(native, nop);
  61. environment = GrpcEnvironment.AddRef();
  62. metadata = MetadataArraySafeHandle.Create(Metadata.Empty);
  63. completionRegistry = new CompletionRegistry(environment, () => environment.BatchContextPool.Lease(), () => throw new NotImplementedException());
  64. var cq = CompletionQueueSafeHandle.CreateAsync(completionRegistry);
  65. call = CreateFakeCall(cq);
  66. }
  67. private static CallSafeHandle CreateFakeCall(CompletionQueueSafeHandle cq)
  68. {
  69. var call = CallSafeHandle.CreateFake(new IntPtr(0xdead), cq);
  70. bool success = false;
  71. while (!success)
  72. {
  73. // avoid calling destroy on a nonexistent grpc_call pointer
  74. call.DangerousAddRef(ref success);
  75. }
  76. return call;
  77. }
  78. [GlobalCleanup]
  79. public void Cleanup()
  80. {
  81. try
  82. {
  83. metadata?.Dispose();
  84. metadata = null;
  85. call?.Dispose();
  86. call = null;
  87. if (environment != null)
  88. {
  89. environment = null;
  90. // cleanup seems... unreliable on CLR
  91. // GrpcEnvironment.ReleaseAsync().Wait(1000);
  92. }
  93. }
  94. catch (Exception ex)
  95. {
  96. Console.Error.WriteLine(ex.Message);
  97. }
  98. }
  99. private CallSafeHandle call;
  100. private MetadataArraySafeHandle metadata;
  101. const int Iterations = 1000;
  102. [Benchmark(OperationsPerInvoke = Iterations)]
  103. public unsafe void SendStatus()
  104. {
  105. for (int i = 0; i < Iterations; i++)
  106. {
  107. call.StartSendStatusFromServer(this, status, metadata, false, SliceBufferSafeHandle.NullInstance, WriteFlags.NoCompress);
  108. }
  109. }
  110. void ISendStatusFromServerCompletionCallback.OnSendStatusFromServerCompletion(bool success) { }
  111. }
  112. }