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.Runtime.InteropServices; 20 using BenchmarkDotNet.Attributes; 21 using Grpc.Core.Internal; 22 23 namespace Grpc.Microbenchmarks 24 { 25 public class PInvokeByteArrayBenchmark : CommonThreadedBase 26 { 27 static readonly NativeMethods Native = NativeMethods.Get(); 28 29 protected override bool NeedsEnvironment => false; 30 31 32 [Params(0)] 33 public int PayloadSize { get; set; } 34 35 const int Iterations = 5 * 1000 * 1000; // High number to make the overhead of RunConcurrent negligible. 36 [Benchmark(OperationsPerInvoke = Iterations)] AllocFree()37 public void AllocFree() 38 { 39 RunConcurrent(RunBody); 40 } 41 RunBody()42 private void RunBody() 43 { 44 var payload = new byte[PayloadSize]; 45 for (int i = 0; i < Iterations; i++) 46 { 47 var gcHandle = GCHandle.Alloc(payload, GCHandleType.Pinned); 48 var payloadPtr = gcHandle.AddrOfPinnedObject(); 49 Native.grpcsharp_test_nop(payloadPtr); 50 gcHandle.Free(); 51 } 52 } 53 } 54 } 55