How can i Get process Cpu usage in c??
I need Cpu usage of evrey process and threads.
please give me an example.
Thanks!
How can i Get process Cpu usage in c??
I need Cpu usage of evrey process and threads.
please give me an example.
Thanks!
In plain C, this is not possible, but since the question is also tagged "Windows":
CPU usage is CPU time divided by real time. The GetThreadTimes and GetProcessTimes functions give you that information (among other features such as performance counters, which Joachim Pileborg mentioned above, but I think this one is probably easier).
You probably also want to use CreateToolhelp32Snapshot first to know what processes and threads exist at all. You'll need to translate thread/process IDs to handles, but I guess that won't be a big hurdle (i.e. OpenProcess
).
In C, total CPU usage can be determined using Performance Counters (there is a small typo in the example code: sleep
has to be changed to Sleep
).
In C++, C#, Delphi etc., I would recommend using WMI.
== EDIT ==
I found an approach to get the per-process CPU usage. For example, in order to get the CPU load of Microsoft Outlook, change the counter path in the above example to this:
PdhAddCounter(query, TEXT("\\Process(OUTLOOK)\\% Processor Time"), 0, &counter);
If you have multiple instances of the same executable running, you may use indexes. This MSDN example is also very useful.