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 为您的测试提供了更多装饰器和配置选项,请参阅文档
如果您确实必须对环境变量进行基准测试,您可以使用 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();
}