본문 바로가기

리눅스

[리눅스] 리눅스에서 CPU 사용률을 계산하고, 소수점 2자리까지 출력하는 쉘 스크립트 예제 - by ChatGPT

반응형

리눅스에서 CPU 사용률을 계산하고, 소수점 2자리까지 출력하는 쉘 스크립트 예제

vim cpu-usage.sh
#!/bin/bash

# Get the CPU statistics from /proc/stat file
cpu_stats=(`cat /proc/stat | grep '^cpu '`) 

# Calculate the total CPU time.
total_cpu_time=0
for stat in "${cpu_stats[@]:1}"; do
  total_cpu_time=$((total_cpu_time + stat))
done

# Calculate the CPU idle time.
cpu_idle_time=${cpu_stats[4]}

# Calculate the CPU usage percentage.
cpu_usage=$(echo "scale=2; 100 * ($total_cpu_time - $cpu_idle_time) / $total_cpu_time" | bc -l)

# Print the CPU usage percentage.
echo "CPU usage: $cpu_usage%"
chmod +x cpu-usage.sh
$ ./cpu-usage.sh
CPU usage: 1.80%

Scripts generated by ChatGPT

728x90
반응형