.NET Core 如何调试 CPU 爆高?
在這篇文章中我們將會分析一個 CPU 爆高的案例,測試demo鏈接 :https://docs.microsoft.com/en-us/samples/dotnet/samples/diagnostic-scenarios/ 。
你將會學到:
如何使用 dotnet-counters 確定真實的 cpu 使用率。
使用 dotnet-trace 追蹤代碼。
使用 PerfView 尋找問題代碼并解決。
確定CPU使用率
首先運行案例程序,參考如下代碼:
dotnet?run接下來使用如下命令找到 netcore 程序的 pid。
dotnet-trace?ps值得注意的是,我這里的 pid=22884, 你的可能不一樣,然后用 dotnet-counters 工具收集當前 cpu 爆高的狀態數據,參考如下命令。
dotnet-counters?monitor?--refresh-interval?1?-p?22884這里的 refresh-interval 表示刷新間隔,接下來你會得到如下輸出。
Press?p?to?pause,?r?to?resume,?q?to?quit.Status:?Running[System.Runtime]%?Time?in?GC?since?last?GC?(%)?????????????????????????0Allocation?Rate?/?1?sec?(B)????????????????????????????0CPU?Usage?(%)??????????????????????????????????????????0Exception?Count?/?1?sec????????????????????????????????0GC?Heap?Size?(MB)??????????????????????????????????????4Gen?0?GC?Count?/?60?sec????????????????????????????????0Gen?0?Size?(B)?????????????????????????????????????????0Gen?1?GC?Count?/?60?sec????????????????????????????????0Gen?1?Size?(B)?????????????????????????????????????????0Gen?2?GC?Count?/?60?sec????????????????????????????????0Gen?2?Size?(B)?????????????????????????????????????????0LOH?Size?(B)???????????????????????????????????????????0Monitor?Lock?Contention?Count?/?1?sec??????????????????0Number?of?Active?Timers????????????????????????????????1Number?of?Assemblies?Loaded??????????????????????????140ThreadPool?Completed?Work?Item?Count?/?1?sec???????????3ThreadPool?Queue?Length????????????????????????????????0ThreadPool?Thread?Count????????????????????????????????7Working?Set?(MB)??????????????????????????????????????63從輸出看,當前的 cpu=0,現在可以讓 cpu 爆高起來了,輸入鏈接:api/diagscenario/highcpu/60000 ,然后重新運行下 dotnet-counters ,啟動時指定 System.Runtime[cpu-usage] 參數表示我們只捕獲 cpu-usage 指標。
dotnet-counters?monitor?--counters?System.Runtime[cpu-usage]?-p?22884?--refresh-interval?1不出意外,你會看到 cpu使用率 上去了。
Press?p?to?pause,?r?to?resume,?q?to?quit.Status:?Running[System.Runtime]CPU?Usage?(%)?????????????????????????????????????????25可以看到,cpu使用率已經高達 25% 了,到這里我認為這個 cpu 使用率已經超出了我的預期,接下來就需要進行代碼追蹤了。
收集運行代碼數據
接下來用 dotnet-trace 作為收集工具,運行如下命令。
dotnet-trace?collect?-p?22884?--providers?Microsoft-DotNETCore-SampleProfiler讓 dotnet-trace 運行大概 20-30s,然后鍵入 Enter 退出,你會看到當前目錄有一個 nettrace 文件,接下來就可以用 PrefView 對 nettrace 進行分析啦。
總結
以上是生活随笔為你收集整理的.NET Core 如何调试 CPU 爆高?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# WPF Caliburn.Micr
- 下一篇: 如何捕获 EF 生成的 SQL 脚本?