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 PInvokeByteArrayBenchmark
30     {
31         static readonly NativeMethods Native = NativeMethods.Get();
32 
Init()33         public void Init()
34         {
35         }
36 
Cleanup()37         public void Cleanup()
38         {
39         }
40 
Run(int threadCount, int iterations, int payloadSize)41         public void Run(int threadCount, int iterations, int payloadSize)
42         {
43             Console.WriteLine(string.Format("PInvokeByteArrayBenchmark: threads={0}, iterations={1}, payloadSize={2}", threadCount, iterations, payloadSize));
44             var threadedBenchmark = new ThreadedBenchmark(threadCount, () => ThreadBody(iterations, payloadSize));
45             threadedBenchmark.Run();
46         }
47 
ThreadBody(int iterations, int payloadSize)48         private void ThreadBody(int iterations, int payloadSize)
49         {
50             var payload = new byte[payloadSize];
51 
52             var stopwatch = Stopwatch.StartNew();
53             for (int i = 0; i < iterations; i++)
54             {
55                 var gcHandle = GCHandle.Alloc(payload, GCHandleType.Pinned);
56                 var payloadPtr = gcHandle.AddrOfPinnedObject();
57                 Native.grpcsharp_test_nop(payloadPtr);
58                 gcHandle.Free();
59             }
60             stopwatch.Stop();
61             Console.WriteLine("Elapsed millis: " + stopwatch.ElapsedMilliseconds);
62         }
63     }
64 }
65