.NET Core 如何調(diào)試 CPU 爆高?
在這篇文章中我們將會(huì)分析一個(gè) CPU 爆高的案例,測(cè)試demo鏈接 :https://docs.microsoft.com/en-us/samples/dotnet/samples/diagnostic-scenarios/ 。
你將會(huì)學(xué)到:
如何使用 dotnet-counters 確定真實(shí)的 cpu 使用率。
使用 dotnet-trace 追蹤代碼。
使用 PerfView 尋找問(wèn)題代碼并解決。
確定CPU使用率
首先運(yùn)行案例程序,參考如下代碼:
dotnet?run
接下來(lái)使用如下命令找到 netcore 程序的 pid。
dotnet-trace?ps
值得注意的是,我這里的 pid=22884, 你的可能不一樣,然后用 dotnet-counters 工具收集當(dāng)前 cpu 爆高的狀態(tài)數(shù)據(jù),參考如下命令。
dotnet-counters?monitor?--refresh-interval?1?-p?22884
這里的 refresh-interval 表示刷新間隔,接下來(lái)你會(huì)得到如下輸出。
Press?p?to?pause,?r?to?resume,?q?to?quit.
????Status:?Running
[System.Runtime]
????%?Time?in?GC?since?last?GC?(%)?????????????????????????0
????Allocation?Rate?/?1?sec?(B)????????????????????????????0
????CPU?Usage?(%)??????????????????????????????????????????0
????Exception?Count?/?1?sec????????????????????????????????0
????GC?Heap?Size?(MB)??????????????????????????????????????4
????Gen?0?GC?Count?/?60?sec????????????????????????????????0
????Gen?0?Size?(B)?????????????????????????????????????????0
????Gen?1?GC?Count?/?60?sec????????????????????????????????0
????Gen?1?Size?(B)?????????????????????????????????????????0
????Gen?2?GC?Count?/?60?sec????????????????????????????????0
????Gen?2?Size?(B)?????????????????????????????????????????0
????LOH?Size?(B)???????????????????????????????????????????0
????Monitor?Lock?Contention?Count?/?1?sec??????????????????0
????Number?of?Active?Timers????????????????????????????????1
????Number?of?Assemblies?Loaded??????????????????????????140
????ThreadPool?Completed?Work?Item?Count?/?1?sec???????????3
????ThreadPool?Queue?Length????????????????????????????????0
????ThreadPool?Thread?Count????????????????????????????????7
????Working?Set?(MB)??????????????????????????????????????63
從輸出看,當(dāng)前的 cpu=0,現(xiàn)在可以讓 cpu 爆高起來(lái)了,輸入鏈接:api/diagscenario/highcpu/60000 ,然后重新運(yùn)行下 dotnet-counters ,啟動(dòng)時(shí)指定 System.Runtime[cpu-usage] 參數(shù)表示我們只捕獲 cpu-usage 指標(biāo)。
dotnet-counters?monitor?--counters?System.Runtime[cpu-usage]?-p?22884?--refresh-interval?1
不出意外,你會(huì)看到 cpu使用率 上去了。
Press?p?to?pause,?r?to?resume,?q?to?quit.
????Status:?Running
[System.Runtime]
????CPU?Usage?(%)?????????????????????????????????????????25
可以看到,cpu使用率已經(jīng)高達(dá) 25% 了,到這里我認(rèn)為這個(gè) cpu 使用率已經(jīng)超出了我的預(yù)期,接下來(lái)就需要進(jìn)行代碼追蹤了。
收集運(yùn)行代碼數(shù)據(jù)
接下來(lái)用 dotnet-trace 作為收集工具,運(yùn)行如下命令。
dotnet-trace?collect?-p?22884?--providers?Microsoft-DotNETCore-SampleProfiler
讓 dotnet-trace 運(yùn)行大概 20-30s,然后鍵入 Enter 退出,你會(huì)看到當(dāng)前目錄有一個(gè) nettrace 文件,接下來(lái)就可以用 PrefView 對(duì) nettrace 進(jìn)行分析啦。

