Processor usage [duplicate]

2019-09-21 11:16发布

问题:

Possible Duplicate:
CPU Usage using WMI & C#

How to retrieve CPU usage % in C# (.NET) using WMI? Yes, without any stupid PerformanceCounter.

回答1:

PerformanceCounter is a very low cost way of retrieving this info. As opposed to WMI which will give you the exact same info but with lots of overhead because it runs on top of COM.

And it has the exact same problem as PC, which is why I'd guess you think it is 'stupid'. CPU usage percent is measured over an interval. Actual CPU usage is either 0 or 100%, the CPU never runs intentionally at a lower rate. It runs code at full bore when there's a thread that has work to do. If there is no work to do, the normal state of your desktop machine, then the CPU is powered off with the HLT instruction. It is woken up again with the clock interrupt.

The CPU usage percentage as shown in TaskMgr or Permon is a calculated value over one second. The ratio of the amount of time it was running at 100% vs the amount of time it was turned off. The interval length is very important. The shorter you make it, the 'jumpier' the calculated value gets. Down to calling NextValue() twice in a row, you'll always get 100%.

Long story short: you need a timer. Make it one second to emulate what you see in PerfMon and TaskMgr.