How Do You Monitor The CPU Utilization of a Process Using PowerShell?

后端 未结 3 1496
别那么骄傲
别那么骄傲 2021-02-03 10:20

I\'m trying to write a PowerShell script to monitor % CPU utilization of a SQL Server process. I\'d like to record snapshots of this number every day so we can monitor it over t

3条回答
  •  温柔的废话
    2021-02-03 11:01

    Your hypothesis is almost correct. A single thread (and a process will always have at least one thread) can have at most 100% for PercentProcessorTime but:

    • A process can have multiple threads.
    • A system can have multiple (logical) CPU cores.

    Hence here (Intel i7 CPU with hyperthreading on) I have 8 logical cores, and the top 20 threads (filtering out totals) shows (with a little tidying up to make it readable):

    PS > gwmi Win32_PerfFormattedData_PerfProc_Thread | 
        ?{$_.Name -notmatch '_Total'} | 
        sort PercentProcessorTime -desc | 
        select -first 20 | 
        ft -auto Name,IDProcess,IDThread,PercentProcessorTime
    
    Name           IDProcess IDThread PercentProcessorTime
    ----           --------- -------- --------------------
    Idle/6                 0        0                  100
    Idle/3                 0        0                  100
    Idle/5                 0        0                  100
    Idle/1                 0        0                  100
    Idle/7                 0        0                   96
    Idle/4                 0        0                   96
    Idle/0                 0        0                   86
    Idle/2                 0        0                   68
    WmiPrvSE/7#1        7420     6548                   43
    dwm/4               2260     6776                    7
    mstsc/2#1           3444     2416                    3
    powershell/7#2      6352     6552                    0
    conhost/0#2         6360     6368                    0
    powershell/5#2      6352     6416                    0
    powershell/6#2      6352     6420                    0
    iexplore/7#1        4560     3300                    0
    Foxit Reader/1       736     5304                    0
    Foxit Reader/2       736     6252                    0
    conhost/1#2         6360     1508                    0
    Foxit Reader/0       736     6164                    0
    

    all of which should add up to something like 800 for the last column.

    But note this is all rounded to integers. Compare with the CPU column of Process Explorer (which doesn't round when View | Show Fractional CPU is selected) over a few processes. Note, much like win32_PerfFormattedData_PerfProc_Process the percentage value is normalised for the core count (and this is only part of the display):

    A lot of processes are using a few hundreds of thousands of cycles, but not enough to round up to a single percent.

    enter image description here

提交回复
热议问题