PInvokeByteArrayBenchmark.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #region Copyright notice and license
  2. // Copyright 2015 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.Runtime.InteropServices;
  18. using System.Threading;
  19. using Grpc.Core;
  20. using Grpc.Core.Internal;
  21. using System.Collections.Generic;
  22. using System.Diagnostics;
  23. namespace Grpc.Microbenchmarks
  24. {
  25. public class PInvokeByteArrayBenchmark
  26. {
  27. static readonly NativeMethods Native = NativeMethods.Get();
  28. public void Init()
  29. {
  30. }
  31. public void Cleanup()
  32. {
  33. }
  34. public void Run(int threadCount, int iterations, int payloadSize)
  35. {
  36. Console.WriteLine(string.Format("PInvokeByteArrayBenchmark: threads={0}, iterations={1}, payloadSize={2}", threadCount, iterations, payloadSize));
  37. var threadedBenchmark = new ThreadedBenchmark(threadCount, () => ThreadBody(iterations, payloadSize));
  38. threadedBenchmark.Run();
  39. }
  40. private void ThreadBody(int iterations, int payloadSize)
  41. {
  42. var payload = new byte[payloadSize];
  43. var stopwatch = Stopwatch.StartNew();
  44. for (int i = 0; i < iterations; i++)
  45. {
  46. var gcHandle = GCHandle.Alloc(payload, GCHandleType.Pinned);
  47. var payloadPtr = gcHandle.AddrOfPinnedObject();
  48. Native.grpcsharp_test_nop(payloadPtr);
  49. gcHandle.Free();
  50. }
  51. stopwatch.Stop();
  52. Console.WriteLine("Elapsed millis: " + stopwatch.ElapsedMilliseconds);
  53. }
  54. }
  55. }