BenchmarkDotNet-新建项目

Benchmark 项目的结构非常简单, 只需要创建最基础的控制台程序即可

dotnet new console -n benchmarkproject

然后添加nuget包应用

dotnet add package BenchmarkDotNet

或者直接修改 benchmarkproject.csproj 文件

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BenchmarkDotNet" Version="0.13.9" />
  </ItemGroup>
</Project>

假设我想要对 string.IsNullOrEmptystring.IsNullOrWhiteSpace 这两个看起来挺像的字符串判空方法进行基准测试, 用以对比两者的资源使用情况和执行效率

public class Test
{
    [Benchmark]
    public void TestEmpty() => string.IsNullOrEmpty("");
    [Benchmark]
    public void TestWhiteSpace() => string.IsNullOrWhiteSpace("");
}

我们需要写两个方法, 分别调用 string.IsNullOrEmptystring.IsNullOrWhiteSpace, 并且为这两个方法标记 [Benchmark] 特性

然后调用 BenchmarkRunner.Run

BenchmarkRunner.Run(typeof(Test));

这样代码就算是写完了

最后在项目目录下执行命令

dotnet run -c Release

然后等待测试结果即可

Method Mean Error StdDev
TestEmpty 0.0121 ns 0.0123 ns 0.0102 ns
TestWhiteSpace 1.7137 ns 0.0306 ns 0.0255 ns
posted @ 2023-10-09 17:25  崩坏的领航员  阅读(16)  评论(0编辑  收藏  举报