为什么需要性能基准测试?
性能基准测试可以帮助程序员对比2个代码段或者方法的性能,这对于代码重写或者重构来说,可以提供一种很好的量化标准。如果没有性能基准测试,很难想象将方法A改为B方法时候,仅凭肉眼如何区分性能的变化。
文章链接 https://www.cnblogs.com/lwqlun/p/9671611.html
代码基准测试(Code Benchmarking)
新建.Net 5控制台应用程序
使用**Nuget**
安装**BenchmarkDotNet**
,或使用命令**PM> Install-Package BenchmarkDotNet**
改造一下**Program**
类
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Threading;
namespace ConsoleApp1
{
public static class InterlockedGenerator
{
private static long _last;
public static long GetNext()
{
return Interlocked.Increment(ref _last);
}
}
public static class LockGenerator
{
private static long _last;
private static readonly object _locker = new();
public static long GetNext()
{
lock (_locker)
return _last++;
}
}
public class InterlockedGeneratorVsLockGenerator
{
[Benchmark]
public long T1()
{
return InterlockedGenerator.GetNext();
}
[Benchmark]
public long T2()
{
return LockGenerator.GetNext();
}
}
public class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<InterlockedGeneratorVsLockGenerator>();
Console.ReadLine();
}
}
}
将启动模式从**DEBUG**
修改为**RELEASE**
,启动项目
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带来的额外开销。