How To Calculate CPU Usage—A Complete Guide!

How To Calculate CPU Usage—A Complete Guide!

When I monitor CPU usage for my own tasks, I use htop on Linux and Task Manager on Windows. For heavy tasks like video rendering, I often see CPU usage hit 100%, which helps me understand when it’s time to upgrade. Real-time monitoring keeps my workflow smooth.

To calculate CPU usage, track the time a process spends in user and system modes (utime and stime) from the /proc/stat file. Convert these values from clock ticks to seconds, then divide the total CPU time by the elapsed time since the process started, multiplying by 100 to get the percentage of CPU usage.

In this article we discuss about “how to calculate cpu usage” 

How to Calculate CPU Usage of a Process: An In-Depth Guide:

How to Calculate CPU Usage of a Process: An In-Depth Guide:
source: pcsite

It is essential to know how much CPU a process uses in order to monitor and troubleshoot system performance. You can identify performance bottlenecks and optimize resource allocation by calculating a process’s CPU utilization. This tutorial offers a comprehensive tutorial on how to use the /proc//stat and /proc/uptime files to determine a process’s CPU utilization on a Linux system. 

1. Overview of the /proc/<pid>/stat File:

In Linux, the /proc directory contains a wealth of information about the system and running processes. Each process has its own subdirectory under /proc, named by its process ID (PID). Inside this subdirectory, the stat file provides detailed status information about the process, including CPU usage.

A simple text file with many values separated by spaces is the stat file. Important figures for computing CPU use are: 

utime (14th value): The number of clock ticks that indicate how long the process has been in user mode. 

Stime (15th value): The duration in clock ticks that the process has spent in kernel mode. 

starttime (22nd value): The process’s start time since the system booted, measured in clock ticks.

Example Command:

You can use the following to see the stat file for the active shell: 

bash

Copy code

cat /proc/$$/stat

This will output various values, including those needed for CPU usage calculation.

Calculating CPU Usage: Detailed Steps:

1. Understanding Clock Ticks and System Uptime

The values in the /proc/<pid>/stat file are given in clock ticks. To convert these values to seconds, you need to know how many clock ticks occur per second on your system. This value can be retrieved using:

bash

Copy code

getconf CLK_TCK

On many systems, this value is 100, but it can vary.

The /proc/uptime file contains the system’s uptime, which is the total amount of time the system has been operating since the last boot. There are two values in this file: 

  • The system uptime in seconds is the first value. 
  • The amount of idle time the system has is the second value. 

2. Converting Values and Calculating CPU Usage

To determine the CPU usage of a process, follow these steps:

Convert Clock Ticks to Seconds: 

Convert the utime, stime, and starttime values from clock ticks to seconds using the CLK_TCK value obtained earlier.

Calculate Elapsed Time: 

Determine how long the process has been running by subtracting the starttime (in seconds) from the system uptime (in seconds).

Compute CPU Usage: 

Add up the seconds from the utime and stime variables to find the total CPU time consumed. For the CPU utilization percentage, divide this total by the amount of time that has passed and multiply the result by 100. 

3. Bash Script for CPU Usage Calculation

The task is made easier by using a Bash script to automate the process. The script that does the necessary calculations is shown below: 

3. Bash Script for CPU Usage Calculation
source: medium

bash

Copy code

#!/bin/bash

# Check if PID is provided

PID=$1

if [ -z “$PID” ]; then

    echo “Usage: $0 PID”

    exit 1

fi

# Extract process statistics

PROCESS_STAT=($(sed -E ‘s/\([^)]+\)/X/’ “/proc/$PID/stat”))

PROCESS_UTIME=${PROCESS_STAT[13]}

PROCESS_STIME=${PROCESS_STAT[14]}

PROCESS_STARTTIME=${PROCESS_STAT[21]}

# Get system uptime

SYSTEM_UPTIME_SEC=$(tr . ‘ ‘ </proc/uptime | awk ‘{print $1}’)

CLK_TCK=$(getconf CLK_TCK)

# Convert clock ticks to seconds

let PROCESS_UTIME_SEC=”$PROCESS_UTIME / $CLK_TCK”

let PROCESS_STIME_SEC=”$PROCESS_STIME / $CLK_TCK”

let PROCESS_STARTTIME_SEC=”$PROCESS_STARTTIME / $CLK_TCK”

# Calculate elapsed time since the process started

let PROCESS_ELAPSED_SEC=”$SYSTEM_UPTIME_SEC – $PROCESS_STARTTIME_SEC”

# Calculate total CPU usage

let PROCESS_USAGE_SEC=”$PROCESS_UTIME_SEC + $PROCESS_STIME_SEC”

let PROCESS_USAGE=”$PROCESS_USAGE_SEC * 100 / $PROCESS_ELAPSED_SEC”

# Output the results

echo “The PID $PID has used ${PROCESS_UTIME_SEC}s in user mode and ${PROCESS_STIME_SEC}s in kernel mode.”

echo “Total CPU usage is ${PROCESS_USAGE_SEC}s.”

echo “The process has been running for ${PROCESS_ELAPSED_SEC}s, so the CPU usage is ${PROCESS_USAGE}%.”

4. Script Explanation

Here’s a breakdown of the Bash script:

PID Check: 

The script starts by checking if a PID was provided. If not, it displays usage instructions.

Extract Statistics: 

It reads and processes the stat file for the given PID, extracting utime, stime, and starttime.

System Uptime and Conversion: 

The script retrieves system uptime and the number of clock ticks per second, then converts process times from clock ticks to seconds.

CPU Usage Calculation: 

It calculates how long the process has been running and computes the CPU usage as a percentage of this time.

Output Results: 

Finally, it prints the CPU time used by the process and the percentage of CPU usage.

How to Calculate CPU Utilization for a Process:

Calculating CPU utilization for a process involves determining how much CPU time a specific process is using in relation to the total elapsed time since it started. This is typically done by extracting the process’s user and system time from the /proc/<pid>/stat file, converting those values from clock ticks to seconds, and dividing the result by the total running time of the process. 

By automating this calculation with a simple Bash script, you can track the CPU usage of any given process in real time.

How to Calculate CPU Utilization in Linux:

In Linux, CPU utilization can be calculated using the /proc/stat and /proc/uptime files. These files provide system-wide statistics on CPU usage, including time spent in user mode, system mode, and idle. You can use tools like top, vmstat, or custom scripts to monitor overall CPU performance. For individual processes, the /proc/<pid>/stat file offers detailed insights into how much CPU a particular process is consuming, allowing you to calculate its CPU usage as a percentage of system uptime.

CPU Utilization Formula in Process Scheduling:

In process scheduling, CPU utilization is the percentage of time the CPU is actively working on processes rather than sitting idle. The basic formula for CPU utilization is:

CPU Utilization=Total CPU time used by the processTotal elapsed time since the process started×100\text{CPU Utilization} = \frac{\text{Total CPU time used by the process}}{\text{Total elapsed time since the process started}} \times 100CPU Utilization=Total elapsed time since the process startedTotal CPU time used by the process​×100

This formula is essential in understanding how system schedulers allocate CPU resources among processes, ensuring efficient multitasking and optimal system performance.

How to Calculate CPU Time:

To calculate the CPU time for a process, you need to consider two key metrics: user time (utime) and system time (stime), both available in the /proc/<pid>/stat file. User time represents the time a process spends executing code in user space, while system time is the time spent in kernel space. 

How to Calculate CPU Time:
source: softwareg

By adding these values and converting from clock ticks to seconds, you can determine how much CPU time a process has consumed during its lifecycle.

Frequently Asked Question:

1. What is a normal CPU usage?

Normal CPU usage is typically 10-30% during idle or light tasks and can reach 70-100% during heavy workloads like gaming or video editing.

2. How do you calculate the total CPU usage of a process? 

Total CPU usage is calculated by dividing the CPU time a process has used by the elapsed time since the process started, then multiplying by 100.

3. What is the formula for calculating utilization? 

The CPU utilization formula is:
Utilization=Total CPU TimeTotal Elapsed Time×100\text{Utilization} = \frac{\text{Total CPU Time}}{\text{Total Elapsed Time}} \times 100Utilization=Total Elapsed TimeTotal CPU Time​×100

4. How is CPU consumption measured? 

CPU consumption is measured by tracking how much time the CPU spends executing a process or system-wide tasks over a given time interval.

5. What is CPU calculation? 

CPU calculation refers to measuring how much processing time a CPU spends executing tasks, often expressed as utilization percentage.

6. What is my CPU rate? 

Your CPU rate, which is typically expressed in GHz, is the frequency or current speed of your processor. This is available through system configurations or utilities such as Linux’s lscpu or Windows’ Task Manager. 

7. How do I calculate CPU usage percentage in Windows? 

In Windows, you can calculate CPU usage using Task Manager, which shows real-time CPU percentage for system processes.

8. How do I calculate my CPU and core? 

Use Task Manager (Windows) or lscpu (Linux) to check how many CPU cores and logical processors your system has.

9. How to find CPU utilization? 

CPU utilization can be found using tools like Task Manager (Windows), top (Linux), or by reading /proc/stat in Linux for detailed metrics.

10. How do I calculate CPU power consumption? 

To calculate CPU power consumption, multiply the CPU’s voltage, current, and time spent under load, or use software like HWMonitor to get real-time values.

11. What is the best way to measure CPU performance? 

CPU performance is best measured by benchmarking tools like Cinebench, Geekbench, or using real-world tests like rendering or gaming to assess speed and efficiency.

Conclusion:

Linux users can determine their CPU consumption as a percentage of total elapsed time by retrieving process times from /proc//stat, using CLK_TCK to convert them from clock ticks to seconds, and then computing the CPU usage. Monitoring is made easier by automating this procedure with a bash script. Through the identification of bottlenecks and the optimal deployment of system resources, CPU utilization aids in performance optimization. 

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *