BenchmarkConfig.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using BenchmarkDotNet.Columns;
  2. using BenchmarkDotNet.Configs;
  3. using BenchmarkDotNet.Environments;
  4. using BenchmarkDotNet.Exporters;
  5. using BenchmarkDotNet.Jobs;
  6. using BenchmarkDotNet.Loggers;
  7. using BenchmarkDotNet.Reports;
  8. namespace Apq.Cfg.Benchmarks;
  9. /// <summary>
  10. /// 自定义基准测试配置
  11. /// 目标:在 10 分钟内完成所有测试,同时保证结果稳定性
  12. /// </summary>
  13. public class BenchmarkConfig : ManualConfig
  14. {
  15. public BenchmarkConfig()
  16. {
  17. // 自定义 Job:5 次预热 + 10 次迭代,平衡速度与准确性
  18. var baseJob = Job.Default
  19. .WithWarmupCount(5)
  20. .WithIterationCount(10)
  21. .WithLaunchCount(1);
  22. // 添加三个运行时
  23. AddJob(baseJob.WithRuntime(CoreRuntime.Core60).WithId(".NET 6.0"));
  24. AddJob(baseJob.WithRuntime(CoreRuntime.Core80).WithId(".NET 8.0"));
  25. AddJob(baseJob.WithRuntime(CoreRuntime.Core90).WithId(".NET 9.0"));
  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. var timestamp = DateTime.Now.ToString("yyyy-MM-dd_HHmmss");
  42. var benchmarkProjectDir = Path.GetDirectoryName(typeof(BenchmarkConfig).Assembly.Location)!;
  43. // 从 bin/Release/net9.0 回退到项目目录
  44. var projectDir = Path.GetFullPath(Path.Combine(benchmarkProjectDir, "..", "..", ".."));
  45. var artifactsPath = Path.Combine(projectDir, "BenchmarkDotNet.Artifacts", timestamp);
  46. WithArtifactsPath(artifactsPath);
  47. }
  48. }