Skip to content

Instantly share code, notes, and snippets.

@dpanter
Last active December 19, 2023 07:50
Show Gist options
  • Save dpanter/756c19aed9af53dcdea7cefcb1b3c8a3 to your computer and use it in GitHub Desktop.
Save dpanter/756c19aed9af53dcdea7cefcb1b3c8a3 to your computer and use it in GitHub Desktop.
cpu_usage_per_core.sh - Outputs per-core CPU use percentage, space separated one-liner.
#!/bin/bash
# cpu_usage_per_core.sh
# Outputs per-core CPU use percentage, space separated one-liner.
# Created 2020-05-14 - updated 2020-08-13
# Written for Siduction (Debian sid based distro)
# By dpanter https://gist.github.com/dpanter
# requires _mpstat_ (provided by Debian package _sysstat_)
# Failsafe for awk arithmetic ops, if locale uses comma decimal separator
LC_NUMERIC="C"
# Find number of cores on the system
CORES=`grep -c processor /proc/cpuinfo`
# Define number of lines to be trimmed from the bottom of mpstat output
COREHEAD=$(($CORES+3))
# Remove while loop to only run once
while :
do
# Print date and time, ISO format
echo -ne `date +"%F %T"`" "
# Output sums up all columns from mpstat except %idle
# mpstat requires a 1 second delay to grab current data!!!
# mpstat -P <cores> <delay> <iterations>
# sed trims the top 4 rows
# head trims the bottom rows
# awk strips the irrelevant columns and sums the rows
LIST=`mpstat -P ALL 1 1 | sed '1,4d' | head -n -$COREHEAD | awk '{print $3,$4,$5,$6,$7,$8,$9,$10,$11}' | awk '{print $1+$2+$3+$4+$5+$6+$7+$8+$9}'`
# Output to single line with a single space as delimiter
echo -ne $LIST '\n'
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment