.Net性能测试工具BenchmarkDotNet学习

​ BenchmarkDotNet 是一个用于性能基准测试的开源框架。它可以让开发人员编写简单易懂的代码,并测量和分析这些代码的性能表现,从而帮助开发人员优化其代码,以达到更高的性能和更好的效率。

源码地址:https://github.com/dotnet/BenchmarkDotNet

NuGet地址:https://www.nuget.org/packages/BenchmarkDotNet

  1. 用起来还比较简单,在对应的method上面打上[Benchmark]标记即可;
  2. 通过var summary = BenchmarkRunner.Run();来启动;
  3. 要求class和method必须是public;
  4. 要求程序必须是Release;
  5. 会自动将程序中打标记的对应模块跑很多遍,最后给出均值和偏差;

项目中添加BenchmarkDotNet

NuGet\Install-Package BenchmarkDotNet -Version 0.13.5
<PackageReference Include="BenchmarkDotNet" Version="0.13.5" />

image-1678354072500

代码示例

代码来源于最近看的冯辉的 《.NET框架设计与实现》附源码:

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;

//运行基准测试
BenchmarkRunner.Run<PgoBenchmarks>();

[Config(typeof(MyEnvVars))]
public class PgoBenchmarks
{
    // 自定义配置环境 "Default vs DPGO"
    class MyEnvVars : ManualConfig
    {
        public MyEnvVars()
        {
            // 使用默认模式
            AddJob(Job.Default.WithId("Default mode"));
            // 使用DPGO模式模式
            AddJob(Job.Default.WithId("Dynamic PGO")
                .WithEnvironmentVariables(
                    new EnvironmentVariable("DOTNET_TieredPGO", "1"),
                    new EnvironmentVariable("DOTNET_TC_QuickJitForLoops", "1"),
                    new EnvironmentVariable("DOTNET_ReadyToRun", "0")));

        }
    }

    [Benchmark]
    [Arguments(6, 100)]
    public int HotColdBasicBlockReorder(int key, int data)
    {
        if (key == 1)
            return data - 5;
        if (key == 2)
            return data += 4;
        if (key == 3)
            return data >> 3;
        if (key == 4)
            return data * 2;
        if (key == 5)
            return data / 1;
        return data; // 默认key为6,所以会使用返回data 
    }
}


运行结果

image-1678354101531

阅读如遇样式问题,请前往个人博客浏览: https://www.raokun.top
拥抱ChatGPT:https://ai.terramours.site
开源项目地址:https://github.com/firstsaofan/TerraMours