具有 2 个不同环境变量的 2 个不同的基准

2 different Benchmarks with 2 different environment variables

尝试在两个不同的 DLL 下对函数进行基准测试,drawManaged(),运行:

如何使用 benchmarkdotnet 执行此操作?

Benchmarkdotnet 将对标有 [Benchmark] 属性的方法进行基准测试。

最好创建一个小实用程序(或您创建的基准项目中的目录)来调用此函数。尝试并限制每次调用之间的所有变量,而不是在本机情况下设置环境变量,然后直接调用 C# 函数,使 [Benchmark] 装饰方法仅调用您想要比较的方法。

你的测试看起来像这样:

    public class DrawManagedVsDrawNative
{
    private DrawManaged drawManaged = new DrawManaged();
    private DrawNative drawNative = new DrawNative();
    private byte[] data;


    [GlobalSetup]
    public void Setup()
    {
       // Some initialization here
    }

    [Benchmark]
    public byte[] DrawManaged() => drawManaged.Draw();

    [Benchmark]
    public byte[] DrawNative() => drawNative.Draw();
}

benchmarkdotnet 为您的测试提供了更多装饰器和配置选项,请参考 docs

如果您确实必须对设置环境变量进行基准测试,您可以使用 ManualConfig 实现创建自定义作业。像这样:

 [Config(typeof(ConfigWithCustomEnvVars))]
    public class DrawManagedVsDrawNative
    {
        private class ConfigWithCustomEnvVars : ManualConfig
        {
            private const string EnvVar = "Env_Var_Sample";

            public ConfigWithCustomEnvVars()
            {
                Add(Job.Core.WithId("Variable not set"));
                Add(Job.Core
                    .With(new[] { new EnvironmentVariable(EnvVar, "1") })
                    .WithId("Variable set"));
            }
        }

    private DrawManaged drawManaged = new DrawManaged();
    private DrawNative drawNative = new DrawNative();
    private byte[] data;


    [GlobalSetup]
    public void Setup()
    {
       // Some initialization here
    }

    [Benchmark]
    public byte[] DrawManaged() => drawManaged.Draw();

    [Benchmark]
    public byte[] DrawNative() => drawNative.Draw();

    }