Calculating CPU usage from the monitoring API

I want to get CPU metrics of a droplet, I used the monitoring API also I used godo golang library I got the metrics for user, system… etc and I did this formula

totalCpu := (userCpu + systemCpu + stealCpu + softirqCpu + irqCpu + niceCpu + iowaitCpu + idleCpu)
idle := (idleCpu * 100) / totalCpu
 cpuUsage := 100 - idleCpu

but the value is not like the one on the CPU graph on the website

thanks in advance

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Bobby Iliev
Site Moderator
Site Moderator badge
May 14, 2023
Accepted Answer

Hi there,

Your formula looks correct. I believe that the crucial part here is to pass the time frame that you want to get the CPU usage for by defining the start and end parameters.

  • start: Timestamp to start metric window. Example: start=1620683817
  • end: Timestamp to end metric window. Example: end=162070541

That way you can define which time period you want the CPU usage for, as if you don’t pass this you will get an average for the complete CPU usage.

Here is a simple bash script as an example:


API_ENDPOINT="$HOST_ID&start=$(date +%s)&end=$(date +%s)"

# Get the metrics
RESPONSE=$(curl -X GET -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" $API_ENDPOINT)

# Parse the metrics
IDLE=$(echo $RESPONSE | jq -r '[.data.result[] | select(.metric.mode == "idle") | .values[0][1]] | add')
TOTAL=$(echo $RESPONSE | jq -r '[.data.result[] | .values[0][1] | tonumber] | add')

echo "IDLE: $IDLE"
echo "TOTAL: $TOTAL"

USED=$(echo "$TOTAL - $IDLE" | bc)

echo "USED: $USED"

ZERO_CHECK=$(echo "$TOTAL == 0" | bc)
if [ $ZERO_CHECK -eq 1 ]
  echo "No change in TOTAL, can't calculate CPU Usage"
  CPU_USAGE=$(echo "scale=2; ($USED / $TOTAL) * 100" | bc)
  echo "CPU Usage: $CPU_USAGE%"

This uses the same formula but gives you the CPU usage for the current time being. I just tested this and it seems to be reporting the same information as in the DigitalOcean Control panel.

Hope that this helps!



Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up