How to calculate CPU usage by PID process in Linux with C?

I want to programmatically [in C] calculate the CPU utilization% for a given process id on Linux.

How can we get% real-time CPU usage for a given process?

To make this clearer:

  • I must be able to determine CPU usage for the provided processid or process.
  • A process should not be a child process.
  • I want a solution in C.
+82
c linux cpu-usage
Sep 14 '09 at 8:58
source share
12 answers

You need to analyze the data from /proc/<PID>/stat . These are the first few fields (from Documentation/filesystems/proc.txt in your kernel source):

 Table 1-3: Contents of the stat files (as of 2.6.22-rc3) .............................................................................. Field Content pid process id tcomm filename of the executable state state (R is running, S is sleeping, D is sleeping in an uninterruptible wait, Z is zombie, T is traced or stopped) ppid process id of the parent process pgrp pgrp of the process sid session id tty_nr tty the process uses tty_pgrp pgrp of the tty flags task flags min_flt number of minor faults cmin_flt number of minor faults with child's maj_flt number of major faults cmaj_flt number of major faults with child's utime user mode jiffies stime kernel mode jiffies cutime user mode jiffies with child's cstime kernel mode jiffies with child's 

You are probably after utime and / or stime . You also need to read the cpu line from /proc/stat , which looks like this:

 cpu 192369 7119 480152 122044337 14142 9937 26747 0 0 

This indicates the cumulative processor time, which was used in different categories, in units of jiffies. You need to take the sum of the values ​​in this row to get the time_total measure.

Read both utime and stime for the process you are interested in and read time_total from /proc/stat . Then sleep a second or so, and read them all again. Now you can calculate the processor usage by the process according to the sampling time, using:

 user_util = 100 * (utime_after - utime_before) / (time_total_after - time_total_before); sys_util = 100 * (stime_after - stime_before) / (time_total_after - time_total_before); 

Make sense?

+132
15 Sep '09 at 0:31
source share

getrusage () can help you determine whether to use the current process or its child.

Update: I do not remember the API. But all the details will be in / proc / PID / stat, so if we can parse it, we can get a percentage.

EDIT: Since CPU% has no direct calculation, you can use sample material here. Read the ctime and utime for the PID at a specific point in time and read the same values ​​again after 1 second. Find the difference and divide by a hundred. You will receive a utility for this process in the last second.

(may be more difficult if there are many processors)

+11
Sep 14 '09 at 9:01
source share

easy step to create zeros like me :)

read the first line of / proc / stat to get total_cpu_usage1

 sscanf(line,"%*s %llu %llu %llu %llu",&user,&nice,&system,&idle); total_cpu_usage1 = user + nice + system + idle; 

read / proc / pid / stat, where pid is the pid of the process that you want to learn about processor usage, for example:

 sscanf(line, "%*d %*s %*c %*d" //pid,command,state,ppid "%*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu" "%lu %lu" //usertime,systemtime "%*ld %*ld %*ld %*ld %*ld %*ld %*llu" "%*lu", //virtual memory size in bytes ....) 

now summarize usertime and system time and get proc_times1

now wait 1 second or more

do it again and get total_cpu_usage2 and proc_times2

formula:

 (number of processors) * (proc_times2 - proc_times1) * 100 / (float) (total_cpu_usage2 - total_cpu_usage1) 

you can get the cpus number from / proc / cpuinfo

+6
Sep 26
source share

I wrote two small C functions based on the answers in cafs to calculate the user usage + cpu core of the process: https://github.com/fho/code_snippets/blob/master/c/getusage.c

+5
Dec 10 2018-10-10
source share

You can read the manpage for proc for more details, but in the end you can read / proc / [number] / stat to get process information. This is also used by the ps command.

All fields and their scanf format specifiers are documented in proc manpag e.

Below is some information from the manpage (it is quite long):

  pid %d The process ID. comm %s The filename of the executable, in parentheses. This is visible whether or not the executable is swapped out. state %c One character from the string "RSDZTW" where R is runâ ning, S is sleeping in an interruptible wait, D is waitâ ing in uninterruptible disk sleep, Z is zombie, T is traced or stopped (on a signal), and W is paging. ppid %d The PID of the parent. pgrp %d The process group ID of the process. session %d The session ID of the process. tty_nr %d The tty the process uses. tpgid %d The process group ID of the process which currently owns the tty that the process is connected to. 
+3
Sep 14 '09 at 9:33
source share

This is my decision...

 /* this program is looking for CPU,Memory,Procs also u can look glibtop header there was a lot of usefull function have fun.. systeminfo.c */ #include <stdio.h> #include <glibtop.h> #include <glibtop/cpu.h> #include <glibtop/mem.h> #include <glibtop/proclist.h> int main(){ glibtop_init(); glibtop_cpu cpu; glibtop_mem memory; glibtop_proclist proclist; glibtop_get_cpu (&cpu); glibtop_get_mem(&memory); printf("CPU TYPE INFORMATIONS \n\n" "Cpu Total : %ld \n" "Cpu User : %ld \n" "Cpu Nice : %ld \n" "Cpu Sys : %ld \n" "Cpu Idle : %ld \n" "Cpu Frequences : %ld \n", (unsigned long)cpu.total, (unsigned long)cpu.user, (unsigned long)cpu.nice, (unsigned long)cpu.sys, (unsigned long)cpu.idle, (unsigned long)cpu.frequency); printf("\nMEMORY USING\n\n" "Memory Total : %ld MB\n" "Memory Used : %ld MB\n" "Memory Free : %ld MB\n" "Memory Buffered : %ld MB\n" "Memory Cached : %ld MB\n" "Memory user : %ld MB\n" "Memory Locked : %ld MB\n", (unsigned long)memory.total/(1024*1024), (unsigned long)memory.used/(1024*1024), (unsigned long)memory.free/(1024*1024), (unsigned long)memory.shared/(1024*1024), (unsigned long)memory.buffer/(1024*1024), (unsigned long)memory.cached/(1024*1024), (unsigned long)memory.user/(1024*1024), (unsigned long)memory.locked/(1024*1024)); int which,arg; glibtop_get_proclist(&proclist,which,arg); printf("%ld\n%ld\n%ld\n", (unsigned long)proclist.number, (unsigned long)proclist.total, (unsigned long)proclist.size); return 0; } makefile is CC=gcc CFLAGS=-Wall -g CLIBS=-lgtop-2.0 -lgtop_sysdeps-2.0 -lgtop_common-2.0 cpuinfo:cpu.c $(CC) $(CFLAGS) systeminfo.c -o systeminfo $(CLIBS) clean: rm -f systeminfo 
+3
Dec 21 '10 at 9:23
source share

Take a look at the pidstat command, it sounds exactly the way you need it.

+2
Sep 14 '09 at 9:55
source share

If you want to control the specified process, this is usually done using scripts. Here is an example of perl. This puts the interest in the same way as the upper ones, and also resets them to one processor. Then, when a process is active, working with 2 threads, CPU utilization can be more than 100%. Take a special look at how processor cores are counted: D then let me show my example:

 #!/usr/bin/perl my $pid=1234; #insert here monitored process PID #returns current process time counters or single undef if unavailable #returns: 1. process counter , 2. system counter , 3. total system cpu cores sub GetCurrentLoads { my $pid=shift; my $fh; my $line; open $fh,'<',"/proc/$pid/stat" or return undef; $line=<$fh>; close $fh; return undef unless $line=~/^\d+ \([^)]+\) \S \d+ \d+ \d+ \d+ -?\d+ \d+ \d+ \d+ \d+ \d+ (\d+) (\d+)/; my $TimeApp=$1+$2; my $TimeSystem=0; my $CpuCount=0; open $fh,'<',"/proc/stat" or return undef; while (defined($line=<$fh>)) { if ($line=~/^cpu\s/) { foreach my $nr ($line=~/\d+/g) { $TimeSystem+=$nr; }; next; }; $CpuCount++ if $line=~/^cpu\d/; } close $fh; return undef if $TimeSystem==0; return $TimeApp,$TimeSystem,$CpuCount; } my ($currApp,$currSys,$lastApp,$lastSys,$cores); while () { ($currApp,$currSys,$cores)=GetCurrentLoads($pid); printf "Load is: %5.1f\%\n",($currApp-$lastApp)/($currSys-$lastSys)*$cores*100 if defined $currApp and defined $lastApp and defined $currSys and defined $lastSys; ($lastApp,$lastSys)=($currApp,$currSys); sleep 1; } 

I hope this helps you with any monitoring. Of course, you should use scanf or other C functions to convert any perl regexpes that I used for source C. Of course, 1 second for sleep is optional. You can use any time. effect, you get an average load for a certain period of time. When you will use it for monitoring, of course, you should set the last values ​​outside. This is necessary because monitoring usually invokes scripts periodically, and the script should complete its work as soon as possible.

+1
May 27 '15 at
source share

how about top level catch (grep-ing) output.

0
Sep 14 '09 at 8:59
source share

Install the psacct or acct package. Then use the sa command to display the processor time used for the various commands. sa man page

Good howto from nixCraft website.

0
Dec 17 '10 at 8:20
source share

I think it's worth looking at the source code for the GNU "time" command. time It displays the user / system processor time along with the real elapsed time. It calls the wait3 / wait4 system call (if available), and otherwise it calls a temporary system call. wait * the system call returns the structural variable "rusage", and the time of the system call returns "tms". In addition, you can take a look at the getrusage system call, which also returns very interesting time information. time

0
Feb 13 '14 at 22:12
source share

Instead of analyzing this from proc, you can use functions such as getrusage () or clock_gettime (), and calculate processor utilization as the ratio or acceleration time and process / thread time used on the processor.

0
Sep 11 '14 at 6:58
source share



All Articles