BenchmarkConfig.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using BenchmarkDotNet.Columns;
  2. using BenchmarkDotNet.Configs;
  3. using BenchmarkDotNet.Exporters;
  4. using BenchmarkDotNet.Jobs;
  5. using BenchmarkDotNet.Loggers;
  6. using BenchmarkDotNet.Reports;
  7. namespace Apq.Cfg.Benchmarks;
  8. /// <summary>
  9. /// 自定义基准测试配置
  10. /// 使用当前运行时进行测试,通过 -f 参数切换目标框架
  11. /// 运行方式:
  12. /// dotnet run -c Release --project benchmarks/Apq.Cfg.Benchmarks -f net8.0 -- --filter *
  13. /// dotnet run -c Release --project benchmarks/Apq.Cfg.Benchmarks -f net10.0 -- --filter *
  14. /// </summary>
  15. public class BenchmarkConfig : ManualConfig
  16. {
  17. public BenchmarkConfig()
  18. {
  19. // 自定义 Job:5 次预热 + 10 次迭代,平衡速度与准确性
  20. // 使用当前运行时(由 -f 参数决定)
  21. var baseJob = Job.Default
  22. .WithWarmupCount(5)
  23. .WithIterationCount(10)
  24. .WithLaunchCount(1);
  25. AddJob(baseJob);
  26. // 添加内存诊断
  27. AddDiagnoser(BenchmarkDotNet.Diagnosers.MemoryDiagnoser.Default);
  28. // 添加导出器
  29. AddExporter(MarkdownExporter.GitHub);
  30. AddExporter(HtmlExporter.Default);
  31. AddExporter(BenchmarkDotNet.Exporters.Csv.CsvExporter.Default);
  32. // 添加列
  33. AddColumn(StatisticColumn.Mean);
  34. AddColumn(StatisticColumn.Error);
  35. AddColumn(StatisticColumn.StdDev);
  36. // 添加控制台日志
  37. AddLogger(ConsoleLogger.Default);
  38. // 设置摘要样式
  39. WithSummaryStyle(SummaryStyle.Default.WithRatioStyle(RatioStyle.Trend));
  40. // 设置输出目录:使用绝对路径,确保结果保存到 benchmarks 项目目录下
  41. // 包含框架名称作为子目录,支持并行运行不同框架的测试
  42. var timestamp = DateTime.Now.ToString("yyyy-MM-dd_HHmm");
  43. // 从 ".NET 8.0.22" 或 ".NET 10.0.1" 提取主版本号 "net8" 或 "net10"
  44. var desc = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription; // ".NET 8.0.22"
  45. var version = desc.Replace(".NET ", "").Split('.')[0]; // "8" 或 "10"
  46. var framework = $"net{version}";
  47. var benchmarkProjectDir = Path.GetDirectoryName(typeof(BenchmarkConfig).Assembly.Location)!;
  48. // 从 bin/Release/netX.0 回退到项目目录
  49. var projectDir = Path.GetFullPath(Path.Combine(benchmarkProjectDir, "..", "..", ".."));
  50. var artifactsPath = Path.Combine(projectDir, "BenchmarkDotNet.Artifacts", timestamp, framework);
  51. WithArtifactsPath(artifactsPath);
  52. }
  53. }