Calculate average

52 views
Skip to first unread message

Sari Khalil

unread,
Sep 21, 2020, 10:25:33 AM9/21/20
to Prometheus Users
I want to calculate an average_something:
definition:
`Gauge average_sth = Gauge("avg", "dont care")`
`Gauge sum_sth = Gauge("sum", "dont care")`
`Gauge count_sth = Gauge("count", "dont care")`
use:
`average_sth.set(sum_sth/count_sth)`
and it throws an exception.
is there a good way to do it?

Brian Candler

unread,
Sep 21, 2020, 10:44:46 AM9/21/20
to Prometheus Users
I am not sure exactly what you're trying to do.

It's not normal to calculate averages in exporters.  Instead you log the raw values, and calculate averages using PromQL queries, e.g.

avg_over_time(foo[30m])

If you want pre-calculated averages, then you do this with recording rules.  It means the exporter doesn't have to care about what period you want to average over, and you can generate averages over multiple time periods at once.

sum_sth/count_sth would not be a useful thing to do in the exporter anyway, since it would only give you the average since the time the exporter started running, which could be months or years, or it could be a very short time period if the exporter was recently restarted.

Sari Khalil

unread,
Sep 21, 2020, 11:01:03 AM9/21/20
to Prometheus Users
Can You please give an example of pre-calculating it (in python)?
I can’t use `avg_over_time(foo[30m]) because my end point does not understand PromQL.

Brian Candler

unread,
Sep 21, 2020, 11:07:13 AM9/21/20
to Prometheus Users
Why do you want to pre-calculate averages in the exporter?  Can you explain your use case?

Sari Khalil

unread,
Sep 21, 2020, 12:13:58 PM9/21/20
to Prometheus Users
I have a function lets assume it is called foo().
I want to calculate number of times it is called, total amount of time it takes to invoke it in all of the times (so if it is called twice and in the first time it took 5 sec to be performed, and the second time 4 seconds then the sum would be 5+4=9), and average time which is total_amount_of_times/total_times_called

Ben Kochie

unread,
Sep 21, 2020, 1:24:19 PM9/21/20
to Sari Khalil, Prometheus Users
In Prometheus, you would create two counters.

foo_requests_total
foo_request_duration_seconds_total 

One you increment by 1 for each request, the other you increment by the duration in seconds for each request.

Then Prometheus collects the data and you take `rate(foo_request_duration_seconds_total[5m]) / rate(foo_requests_total[5m])`. This would give you the average latency of requests.


--
You received this message because you are subscribed to the Google Groups "Prometheus Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to prometheus-use...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/prometheus-users/310908bf-727f-48f1-a665-2acec01cc821n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages