I followed this docs: https://docs.digitalocean.com/reference/api/api-reference/#operation/monitoring_get_DropletCpuMetrics And I got data like this:
{
"status": "success",
"data": {
"resultType": "matrix",
"result": [
{
"metric": {
"host_id": host_id,
"mode": "idle"
},
"values": [
[
1708955160,
"836680.1399999999"
],
[
1708955280,
"836918.48"
]
]
},
{
"metric": {
"host_id": host_id,
"mode": "iowait"
},
"values": [
[
1708955160,
"529.21"
],
[
1708955280,
"529.51"
]
]
},
{
"metric": {
"host_id": host_id,
"mode": "irq"
},
"values": [
[
1708955160,
"0"
],
[
1708955280,
"0"
]
]
},
{
"metric": {
"host_id": host_id,
"mode": "nice"
},
"values": [
[
1708955160,
"18.490000000000002"
],
[
1708955280,
"18.490000000000002"
]
]
},
{
"metric": {
"host_id": host_id,
"mode": "softirq"
},
"values": [
[
1708955160,
"24.68"
],
[
1708955280,
"24.689999999999998"
]
]
},
{
"metric": {
"host_id": host_id,
"mode": "steal"
},
"values": [
[
1708955160,
"102.99000000000001"
],
[
1708955280,
"103.00999999999999"
]
]
},
{
"metric": {
"host_id": host_id,
"mode": "system"
},
"values": [
[
1708955160,
"759.1199999999999"
],
[
1708955280,
"759.5699999999999"
]
]
},
{
"metric": {
"host_id": host_id,
"mode": "user"
},
"values": [
[
1708955160,
"948.6099999999999"
],
[
1708955280,
"949.23"
]
]
}
]
}
}
How can I calculate the cpu% usage? this is my function:
def get_cpu_usage(host_id, start_time, end_time, token)
uri = URI("https://api.digitalocean.com/v2/monitoring/metrics/droplet/cpu")
uri.query = URI.encode_www_form({ host_id: host_id, start: start_time, end: end_time })
request = Net::HTTP::Get.new(uri)
request["Content-Type"] = "application/json"
request["Authorization"] = "Bearer #{token}"
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
if response.code == '200'
data = JSON.parse(response.body)
else
puts "Failed to fetch droplet metrics. HTTP Error #{response.code}: #{response.message}"
end
end
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!
Hi there, Yuval!
Great to see you diving into monitoring metrics for your Ruby on Rails application!
I’ve answered a similar question in the base but using Bash instead of Ruby:
The key to calculating CPU usage is to focus on how much time the CPU spends performing different types of work, compared to being idle.
Your goal is to calculate the percentage of time the CPU is used, excluding the idle time. Here’s a breakdown of how you can approach this in Ruby, taking inspiration from the bash script example I’ve shared before:
Fetch the Data: You’ve already got this part covered with your get_cpu_usage method, which fetches the CPU metrics for a specified host and time frame.
Parse the Metrics: Once you have the response, you need to parse the JSON and extract the necessary values to calculate the CPU usage. You’ll focus on the ‘values’ part of each metric, which contains timestamps and the corresponding metric values.
Calculate Total and Idle Times: You need to calculate the total CPU time available and the time spent in the ‘idle’ mode. Since your data gives you snapshots at two different times, you can calculate the difference in ‘idle’ time and the total time across all modes between these two snapshots to get the CPU activity within that timeframe.
Compute CPU Usage Percentage: With the total and idle times calculated, you can then compute the CPU usage percentage as (total time - idle time) / total time * 100.
Here is a basic example that you can use as a starting point:
# Assuming 'data' is the parsed JSON response body from your method
def calculate_cpu_usage(data)
# Initialize variables to store total and idle times
total_time_diff = 0
idle_time_diff = 0
# Calculate the difference between the two snapshots for each mode
data["result"].each do |metric|
first_value = metric["values"][0][1].to_f
last_value = metric["values"][-1][1].to_f
diff = last_value - first_value
# Add to total time diff
total_time_diff += diff
# Add to idle time diff if mode is idle
idle_time_diff += diff if metric["metric"]["mode"] == "idle"
end
# Compute CPU usage percentage
cpu_usage = 100 * (total_time_diff - idle_time_diff) / total_time_diff
return cpu_usage.round(2) # Round to 2 decimal places for readability
end
This Ruby method follows the logic of the bash script example from the post above. It calculates the CPU usage percentage over the timeframe between the two snapshots provided for each metric.
Hope that helps and happy coding!
Best,
Bobby
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.