2

How can i Get process Cpu usage in c??

I need Cpu usage of evrey process and threads.

please give me an example.

Thanks!

Ali Kiani
  • 51
  • 1
  • 1
  • 5
  • You can't do this in standard C. You need to use implementation specific libraries. Since you included the windows tag, do you mean that you want to use the windows API rather than "just C"? – David Heffernan Jun 20 '12 at 11:39
  • You might be interested in [performance counters](http://msdn.microsoft.com/en-us/library/windows/desktop/aa373083%28v=vs.85%29.aspx). – Some programmer dude Jun 20 '12 at 11:40
  • It's possible I have alrady develope that, For answere i have a question, How many processor do you have on the computer ? and do you have linux or windows ? – JMBise Jun 20 '12 at 11:46

2 Answers2

3

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).

Damon
  • 67,688
  • 20
  • 135
  • 185
3

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.

Community
  • 1
  • 1
kol
  • 27,881
  • 12
  • 83
  • 120
  • The link to _performance counters_ appears dead, should it perhaps link to https://learn.microsoft.com/en-au/windows/desktop/PerfCtrs/collecting-performance-data instead? – Tas Feb 13 '19 at 02:58
  • 1
    the link has been dead. Archived version: http://web.archive.org/web/20150307162536/http://en.literateprograms.org/CPU_usage_using_performance_counters_(C,_Windows_2000) – phuclv Sep 23 '19 at 09:35