How to get the CPU Usage in C?

c cpu
16,828

Solution 1

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:

Solution 2

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

Solution 3

It is usually operating system specific.

You could use the clock function, returning a clock_t (some integer type, like perhaps long). On Linux systems it measures the CPU time in microseconds.

Share:
16,828
Ronin
Author by

Ronin

Updated on June 12, 2022

Comments

  • Ronin
    Ronin almost 2 years

    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.

  • TOMKA
    TOMKA over 12 years
    clock_t is an arithmetic type, so it could also be double or float.
  • Ronin
    Ronin over 12 years
    what u suggest is :: Retrieves timing information for the specified process. .... but i need to get the total CPU usage (percentage) - like we see in the task manager..... can you help ??
  • Mysticial
    Mysticial over 12 years
    Those can be used to give you the CPU time used. To get the % CPU usage, you will need to divide it by the # of logical cores that the OS sees.
  • David X
    David X over 12 years
    To get get the CPU % usage you would need ( CPU time / # of cores / wall-clock time elapsed ), but otherwise correct.
  • Mysticial
    Mysticial over 12 years
    Oh right, I forgot the wall-clock part as well! Thanks for pointing that out. :)