为什么需要性能基准测试?

性能基准测试可以帮助程序员对比2个代码段或者方法的性能,这对于代码重写或者重构来说,可以提供一种很好的量化标准。如果没有性能基准测试,很难想象将方法A改为B方法时候,仅凭肉眼如何区分性能的变化。

文章链接 https://www.cnblogs.com/lwqlun/p/9671611.html

代码基准测试(Code Benchmarking)

新建.Net 5控制台应用程序
image.png
使用**Nuget**安装**BenchmarkDotNet**,或使用命令**PM> Install-Package BenchmarkDotNet**

改造一下**Program**

  1. using BenchmarkDotNet.Attributes;
  2. using BenchmarkDotNet.Running;
  3. using System;
  4. using System.Threading;
  5. namespace ConsoleApp1
  6. {
  7. public static class InterlockedGenerator
  8. {
  9. private static long _last;
  10. public static long GetNext()
  11. {
  12. return Interlocked.Increment(ref _last);
  13. }
  14. }
  15. public static class LockGenerator
  16. {
  17. private static long _last;
  18. private static readonly object _locker = new();
  19. public static long GetNext()
  20. {
  21. lock (_locker)
  22. return _last++;
  23. }
  24. }
  25. public class InterlockedGeneratorVsLockGenerator
  26. {
  27. [Benchmark]
  28. public long T1()
  29. {
  30. return InterlockedGenerator.GetNext();
  31. }
  32. [Benchmark]
  33. public long T2()
  34. {
  35. return LockGenerator.GetNext();
  36. }
  37. }
  38. public class Program
  39. {
  40. static void Main(string[] args)
  41. {
  42. BenchmarkRunner.Run<InterlockedGeneratorVsLockGenerator>();
  43. Console.ReadLine();
  44. }
  45. }
  46. }

将启动模式从**DEBUG**修改为**RELEASE**,启动项目
image.png

benchmark 输出表格是什么意思

Method Mean Error StdDev
T1 6.068 ns 0.0266 ns 0.0236 ns
T2 18.123 ns 0.0280 ns 0.0234 ns
  • Mean 的意思是 Arithmetic mean of all measurements 所有测量的算术平均值
  • Error 的意思是 Half of 99.9% confidence interval 99.9% 一半的置信度区间
  • StdDev 是所有测量的标准偏差

在测试过程包括
Pilot: 决定运行几次。
IdleWarmup, IdleTarget:评估BenchmarkDotNet这个工具带来的额外开销。
MainWarmup:测试热身。
MainTarget:测试。
Result:测试结果减去BenchmarkDotNet带来的额外开销。