BenchmarkUtil.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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.Collections.Concurrent;
  18. using System.Collections.Generic;
  19. using System.Diagnostics;
  20. using System.Threading.Tasks;
  21. namespace Grpc.Core.Utils
  22. {
  23. /// <summary>
  24. /// Utility methods to run microbenchmarks.
  25. /// </summary>
  26. public static class BenchmarkUtil
  27. {
  28. /// <summary>
  29. /// Runs a simple benchmark preceded by warmup phase.
  30. /// </summary>
  31. public static void RunBenchmark(int warmupIterations, int benchmarkIterations, Action action)
  32. {
  33. var logger = GrpcEnvironment.Logger;
  34. logger.Info("Warmup iterations: {0}", warmupIterations);
  35. for (int i = 0; i < warmupIterations; i++)
  36. {
  37. action();
  38. }
  39. logger.Info("Benchmark iterations: {0}", benchmarkIterations);
  40. var stopwatch = new Stopwatch();
  41. stopwatch.Start();
  42. for (int i = 0; i < benchmarkIterations; i++)
  43. {
  44. action();
  45. }
  46. stopwatch.Stop();
  47. logger.Info("Elapsed time: {0}ms", stopwatch.ElapsedMilliseconds);
  48. logger.Info("Ops per second: {0}", (int)((double)benchmarkIterations * 1000 / stopwatch.ElapsedMilliseconds));
  49. }
  50. }
  51. }