從火焰圖(Flame Graph)讀懂你的 .NET 應用程式效能瓶頸
當 APM 指標告訴你「慢」,但你不知道「為什麼」 你的監控儀表板亮起了紅燈——P99 延遲突破 2 秒,GC 暫停時間激增,CPU 使用率在 80% 附近徘徊。你翻遍了 Application Insights 的 Trace,看到的是一串串 HttpClient 呼叫和 SQL 查詢,卻找不到真正的根因。 這正是火焰圖(Flame Graph)派上用場的時刻。 火焰圖不是新技術——Brendan Gregg 在 Netflix 工作期間將其推廣,最初用於 Linux CPU profiling。但在 .NET 生態系中,隨著 dotnet-trace、PerfView、以及 Visual Studio Profiler 的成熟,它已成為定位效能瓶頸最直接的工具。本文將帶你從工具鏈建立到實戰解讀,完整走一遍 .NET 火焰圖分析流程。 先決條件與背景知識 環境需求 .NET 8 SDK(dotnet --version 應顯示 8.x.x 以上) dotnet-trace 全域工具:dotnet tool install --global dotnet-trace dotnet-counters:dotnet tool install --global dotnet-counters dotnet-gcdump:dotnet tool install --global dotnet-gcdump SpeedScope(瀏覽器版):speedscope.app 或 PerfView 2.0.x(Windows 限定,功能最完整) 你需要理解的核心概念 Sampling vs Instrumentation Profiling 火焰圖通常基於 sampling profiler:每隔固定時間間隔(例如 1ms)對所有執行緒抓一次 call stack snapshot。這個方式開銷極低(通常 < 5% CPU overhead),適合在 staging 甚至 production 環境使用。 相較之下,instrumentation profiler 在每個函式進出點插樁,精確度高但開銷大——不適合線上使用。 CLR 的 EventPipe 機制 自 .NET Core 2.1 起,CLR 內建 EventPi...