Linux下如何获取等待CPU的进程数及单独统计等待进程数?
Hey there, let's break down your two Linux process metric questions clearly—these are key for debugging CPU bottlenecks!
There are a couple of practical ways to calculate this:
Method 1: Combine
vmstatand CPU core count
First, usevmstatto get the total number of runnable processes (both running on CPU and waiting for CPU time):vmstat 1 1 | awk 'NR==3 {print $1}'This pulls the value from the
rcolumn (the third row is the actual data after headers). Then get your system's online CPU core count:nprocSince each CPU core can only run one process at a time, the number of processes waiting for CPU is simply the total runnable count minus the core count (if the total is larger than the core count; otherwise, it's 0). Here's a quick one-liner to compute it directly:
r=$(vmstat 1 1 | awk 'NR==3 {print $1}'); cores=$(nproc); wait=$(( r > cores ? r - cores : 0 )); echo "Processes waiting for CPU: $wait"Method 2: Verify with
ps
You can count all processes in the runnable state (R state) usingps:ps -eo state | grep -c '^R'This number matches the
rvalue fromvmstat. Subtract your CPU core count from this number, and you'll get the count of processes waiting for CPU time.
vmstat's r column? First, let's cover getting the run queue size:
Using
vmstat
As you noted, thercolumn invmstatdirectly represents the run queue size (total runnable processes: running + waiting for CPU). To fetch it quickly:vmstat 1 1 | awk 'NR==3 {print $1}'The
1 1means we take one sample with a 1-second interval, skipping the header rows.Using
top
In thetopoutput, look at theTasksline—therunningvalue is the run queue size. You can also grab it via command-line mode:top -b -n 1 | grep 'Tasks:' | awk '{print $4}'
Now, for isolating the number of processes waiting for CPU from vmstat's r value:
The r column counts both processes actively running on CPU and those waiting in the run queue. Since each CPU core can only execute one process at a time, the waiting process count is:
Waiting processes = Total runnable processes (r value) - Number of online CPU cores
If the r value is less than or equal to your core count, that means all runnable processes are actively using CPU—there are no processes waiting.
For example:
- If you have a 4-core system and
vmstatshowsr=6, then 6-4=2 processes are waiting for CPU. - If
r=3on the same 4-core system, there are 0 waiting processes.
You can also use pidstat to inspect individual processes, but it's less efficient for a quick count—pidstat -u 1 1 shows CPU usage per process, and processes in R state with low CPU usage are likely waiting for CPU time.
内容的提问来源于stack exchange,提问作者Joey Yi Zhao

