Can a C# program measure its own CPU usage somehow?

Lasse V. Karlsen picture Lasse V. Karlsen · Nov 9, 2008 · Viewed 30.1k times · Source

I am working on a background program that will be running for a long time, and I have a external logging program (SmartInspect) that I want to feed with some values periodically, to monitor it in realtime when debugging.

I know I can simply fire up multiple programs, like the Task Manager, or IARSN TaskInfo, but I'd like to keep everything in my own program for this, as I also wants to add some simple rules like if the program uses more than X% CPU, flag this in the log.

I have a background thread that periodically feeds some statistics to SmartInspect, like memory consumption, working set, etc.

Is it possible for this thread to get a reasonably accurate measure of how much of the computer's CPU resources it consumes? The main program is a single-threaded application (apart from the watchdog thread that logs statistics) so if a technique is limited to how much does a single thread use then that would be good too.

I found some entries related to something called rusage for Linux and C. Is there something similar I can use for this?


Edit: Ok, I tried the performance counter way, but it added quite a lot of GC-data each time called, so the graph for memory usage and garbage collection skyrocketed. I guess I'll just leave this part out for now.

Answer

axk picture axk · Nov 9, 2008

You can also use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.