Question

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:

#!/bin/bash

TOKEN="your_digitalocean_token"
HOST_ID="your_host_id"
API_ENDPOINT="https://api.digitalocean.com/v2/monitoring/metrics/droplet/cpu?host_id=$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 ]
then
  echo "No change in TOTAL, can't calculate CPU Usage"
else
  CPU_USAGE=$(echo "scale=2; ($USED / $TOTAL) * 100" | bc)
  echo "CPU Usage: $CPU_USAGE%"
fi

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!

Best,

Bobby

For anyone else coming across this question and also coming in with, like me, very little knowledge of what the stats returned by the OS mean, this might help.

In order to determine CPU % from the data returned from the CPU Monitoring API it is required to calculate it based on the difference between 2 data points divided by the time between the 2 data points, then convert to a percentage.

You can calculate the total as per the OP’s calculation for a given data point, and also obtain the idle value for that data point.

Then you can do something like this, which I’m providing as an example of what I needed to do:

const totalCpuDiff = dataPoint.totalCpu - previousDataPoint.totalCpu;
const idleCpuDiff = dataPoint.idleCpu - previousDataPoint.idleCpu;
const timeDiff = dataPoint.timeStamp - previousDataPoint.timeStamp;
const cpuUsagePercent = ((totalCpuDiff-idleCpuDiff)/timeDiff)*100;

Something like this will give you the CPU percentage for that one data point. If your request returns many data points you can iterate through the API response to obtain CPU usage over time.

Try DigitalOcean for free

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

Sign up

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel