2

I want to calculate current cpu usage for particular application in my code. I looked up on internet and found pdh library for windows. When I tried it I am getting overall cpu usage not cpu usage for one process.

PdhAddCounter(hquery, TEXT("\\Processor(_Total)\\% Processor Time"),0,&counter);

So what I do with this line to get cpu usage for particular process? I tried replacing _Total with process name(explorer). At that time I am getting 0 cpu usage. But I checked in resource monitor that opening many windows at a time increased cpu usage upto 20%. Still in log file cpu usage is showing 0.

Can anyone help me with this?

thanks in advance.

Darshan
  • 151
  • 5
  • 13

2 Answers2

3

You need to use GetProcessTimes

And unfortunately, it won't give you the "CPU usage", it will give you the amount of CPU-time since the process started. So to get CPU usage, you will need to take one sample, store that, and then take another sample a known amount of time later, and then calculate the time (and if you want to know the total usage, you'll need to add the usertime and kerneltime together, of course).

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • Thanks for your response. But I think you didn't understand or I didn't explain well. Suppose chrome.exe is one process. At any time some process is taking some percentage of cpu usage.It is shown in resource monitor under cpu tab for every process individually. I want that number.I have separate thread for that. So I want cpu usage for particular process(i.e. chrome.exe in this case). And by total means overall cpu usage consume by all process that we can see in task-manager. – Darshan Aug 07 '13 at 07:22
  • And what I suggested will give you that. You will have to do a little bit of coding to work out the percentage (and the handle of the process you are interested in). – Mats Petersson Aug 07 '13 at 07:25
  • I got another way to do it. – Darshan Aug 07 '13 at 09:55
  • 1
    @Darshan: You can post your solution as an answer to help others and also get points. – Isaac Apr 05 '14 at 14:25
-4

You can check this for example. Explained everything in that project. It will give memory based on process id(same way shown in task manager)

Thanks, Darshan

Darshan
  • 151
  • 5
  • 13