When running inside an LXC container, traditional tools like top may not accurately reflect CPU usage because they can be limited by the container's view of system resources. Instead, a more precise and efficient method involves directly reading CPU statistics from the system files or cgroup interfaces. Here's how you can achieve this:
1. Using /proc/stat
You can create a simple Bash one-liner that reads CPU usage from /proc/stat twice with a short interval and calculates the difference to determine CPU usage:
bash -c '
read cpu a b c idle rest < /proc/stat
prev_idle=$idle
prev_total=$((a + b + c + idle + rest))
sleep 0.1
read cpu a b c idle rest < /proc/stat
curr_idle=$idle
curr_total=$((a + b + c + idle + rest))
delta_total=$((curr_total - prev_total))
delta_idle=$((curr_idle - prev_idle))
usage=$(echo "scale=2; (1 - $delta_idle / $delta_total) * 100" | bc)
echo "CPU Usage: $usage%"
'
Explanation:
- First Read: Capture the initial CPU times.
- Sleep: Wait for a short interval (e.g., 100 milliseconds).
- Second Read: Capture the CPU times again.
- Calculate Differences: Determine the change in total and idle times.
- Compute Usage: Calculate the CPU usage percentage based on the differences.
2. Using Cgroups (Recommended for Containers)
Containers typically use cgroups to limit resources. You can read CPU usage directly from cgroup files, which provides a more accurate measurement within the container.
For cgroups v1:
bash -c '
c1=$(cat /sys/fs/cgroup/cpuacct/cpuacct.usage)
sleep 0.1
c2=$(cat /sys/fs/cgroup/cpuacct/cpuacct.usage)
delta=$((c2 - c1))
# Convert nanoseconds to percentage (assuming single CPU)
usage=$(echo "scale=2; $delta / 100000000 * 100" | bc)
echo "CPU Usage: $usage%"
'
For cgroups v2:
bash -c '
c1=$(awk "/usage_usec/ {print \$2}" /sys/fs/cgroup/cpu.stat)
sleep 0.1
c2=$(awk "/usage_usec/ {print \$2}" /sys/fs/cgroup/cpu.stat)
delta=$((c2 - c1))
# Convert microseconds to percentage (assuming single CPU and 100ms interval)
usage=$(echo "scale=2; $delta / 100000 * 100" | bc)
echo "CPU Usage: $usage%"
'
Notes:
- Interval Adjustment: The
sleep duration can be adjusted for finer granularity, but shorter intervals may lead to less accurate readings.
- Multiple CPUs: If your container has multiple CPUs, you may need to adjust the calculation to account for that (e.g., by dividing by the number of CPUs).
3. Using mpstat (If Available)
If you have the sysstat package installed, you can use mpstat to get CPU usage:
mpstat 0.1 1 | awk '/Average/ {print 100 - $NF"%"}'
Explanation:
mpstat 0.1 1: Samples CPU usage once after 100 milliseconds.
awk '/Average/ {print 100 - $NF"%"}': Calculates CPU usage by subtracting the idle percentage from 100%.
Installation:
If mpstat is not installed, you can install it using:
sudo apt-get install sysstat # For Debian/Ubuntu
sudo yum install sysstat # For CentOS/RHEL
Conclusion
For the best combination of execution speed and precision, especially within an LXC container, reading directly from cgroup files is recommended. This method minimizes overhead and provides accurate resource usage tailored to the container's limits.
Example Script:
Here's a reusable script you can use to get CPU usage within an LXC container:
#!/bin/bash
# Function to get CPU usage using cgroups v1 or v2
get_cpu_usage() {
if [ -f /sys/fs/cgroup/cpuacct/cpuacct.usage ]; then
# cgroups v1
c1=$(cat /sys/fs/cgroup/cpuacct/cpuacct.usage)
sleep 0.1
c2=$(cat /sys/fs/cgroup/cpuacct/cpuacct.usage)
delta=$((c2 - c1))
usage=$(echo "scale=2; $delta / 100000000 * 100" | bc)
elif grep -q "cpu.stat" /proc/self/cgroup 2>/dev/null; then
# cgroups v2
c1=$(awk "/usage_usec/ {print \$2}" /sys/fs/cgroup/cpu.stat)
sleep 0.1
c2=$(awk "/usage_usec/ {print \$2}" /sys/fs/cgroup/cpu.stat)
delta=$((c2 - c1))
usage=$(echo "scale=2; $delta / 100000 * 100" | bc)
else
echo "Cannot determine cgroup version."
exit 1
fi
echo "CPU Usage: $usage%"
}
get_cpu_usage
Usage:
- Save the script to a file, e.g.,
cpu_usage.sh.
- Make it executable:
chmod +x cpu_usage.sh.
- Run it:
./cpu_usage.sh.
This script automatically detects the cgroup version and calculates CPU usage accordingly.