C#中使用BeachmarkDotNet进行基准测试
安装
- 在VS2022中选择菜单项
工具->NuGet包管理->管理解决方案的NuGet程序包 - 在打开的窗口中选择
浏览->搜索BenchmarkDotNet->选择搜索结果中的BenchmarkDotNet->点击安装 - 所有弹出框都选择确定
 - 等待完成安装
 
使用
- 创建一个的类,里面存放需要测试的函数
Test1()和Test2()。1
2
3
4
5
6
7
8
9
10
11
12public class BenchmarkTest
{
public void Test1()
{
Console.WriteLine("Test1");
}
public void Test2()
{
Console.WriteLine("Test2");
}
} - 对需要测试的函数增加
[Benchmark]特性。1
2
3
4
5
6
7
8
9
10
11
12
13
14public class BenchmarkTest
{
[]
public void Test1()
{
Console.WriteLine("Test1");
}
[]
public void Test2()
{
Console.WriteLine("Test2");
}
} - 在
main函数中使用BenchmarkRunner.Run<BenchmarkTest>(),将会调用BenchmarkTest类中的待测试的函数。 
1  | static void Main(string[] args)  | 
- (可选)如果需要查看内存使用可以在class加上
[MemoryDiagnoser]特性。 
1  | []  | 
- 将解决方案配置由
Debug改为Release。 - 点击界面按钮
开始执行(不调试)或者快捷键Ctrl+F5,开始执行。