Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the CPU Usage in C?

Tags:

c

cpu

I want to get the overall total CPU usage for an application in C, the total CPU usage like we get in the TaskManager... I want to know ... for windows and linux :: current Total CPU utilization by all processes ..... as we see in the task manager.

like image 909
Ronin Avatar asked Dec 14 '11 08:12

Ronin


2 Answers

This is platform-specific:

  • In Windows, you can use the GetProcessTimes() function.
  • In Linux, you can actually just use clock().

These can be used to measure the amount of CPU time taken between two time intervals.

EDIT :

To get the CPU consumption (as a percentage), you will need to divide the total CPU time by the # of logical cores that the OS sees, and then divided by the total wall-clock time:

% CPU usage = (CPU time) / (# of cores) / (wall time)

Getting the # of logical cores is also platform-specific:

  • Windows: GetSystemInfo()
  • Linux: sysconf(_SC_NPROCESSORS_ONLN)
like image 120
Mysticial Avatar answered Oct 24 '22 04:10

Mysticial


Under POSIX, you want getrusage(2)'s ru_utime field. Use RUSAGE_SELF for just the calling process, and RUSAGE_CHILDEN for all terminated and wait(2)ed-upon children. Linux also supports RUSAGE_THREAD for just the calling thread. Use ru_stime if you want the system time, which can be summed with ru_utime for total time actively running (not wall time).

like image 30
nick black Avatar answered Oct 24 '22 03:10

nick black