2

I'd like to get the specific CPU Usage of a process under Linux in C++. However, apart from reading

/proc/stat

I don't know how to do that.

If I read this file, then I don't know how I can't get the CPU usage of my current process when I launch the program ...

I want to get the CPU usage of the program I'm running, do you have any clue on how to do it ? I've seen complex solution on the site and I haven't understood them all ... I just need a direction.

It seems my /proc/pid/stat file isn't changing after sleep(2), is that normal ?

Mike Telson
  • 127
  • 2
  • 2
  • 7
  • Look here http://stackoverflow.com/questions/1420426/calculating-cpu-usage-of-a-process-in-linux – Davide Berra Mar 28 '13 at 10:25
  • Notice that there are a lot of directories in `/proc` that are named as a number? They are the same as all process identifiers running, and each directory contain lots of files with information about that specific process. – Some programmer dude Mar 28 '13 at 10:26
  • How abt this?http://stackoverflow.com/questions/3017162/how-to-get-total-cpu-usage-in-linux-c?rq=1 – Ritesh Kumar Gupta Mar 28 '13 at 10:28
  • But ... there's something I don't understand in those topics. Does /proc/stat contains the CPU usage of my CURRENT process ? – Mike Telson Mar 28 '13 at 10:32
  • @Mike: `/proc//stat` – Mat Mar 28 '13 at 10:34
  • `double getcurrusage() { for (int i=0; i<1000000000;++i); return 1.0; }` – Nicholas Wilson Mar 28 '13 at 10:39
  • Do you mean the usage as a percentage or as the cpu time you have used. – Joni Mar 28 '13 at 12:54
  • Both. I mean both. I've tryed the solution given by first comment. However in my file "/proc/pid/stat", after the sleep(2), the data don't change ... is that normal ? I can't calculate CPU usage if it doesn't change ... do you know what's the problem ? – Mike Telson Mar 28 '13 at 13:00

1 Answers1

1

You can use the times system call, which gives the time spent by the CPU on a given process. Try this tutorial, Linux process execution time.

kjohri
  • 1,166
  • 11
  • 10