]> git.ipfire.org Git - thirdparty/collectd.git/commitdiff
cpu plugin: Implement `usage_global_ratio()`.
authorFlorian Forster <octo@collectd.org>
Fri, 5 Jan 2024 09:08:46 +0000 (10:08 +0100)
committerFlorian Forster <octo@collectd.org>
Mon, 22 Jan 2024 15:07:57 +0000 (16:07 +0100)
src/cpu.c
src/cpu_test.c

index b13e0c78f0d7650a29e27e36b1c7843e5eb2e64b..3d364443bceb135b036212ccabc8eba2d153a19a 100644 (file)
--- a/src/cpu.c
+++ b/src/cpu.c
@@ -475,6 +475,12 @@ __attribute__((unused)) static gauge_t usage_ratio(usage_t u, size_t cpu,
   return usage_rate(u, cpu, state) / global_rate;
 }
 
+__attribute__((unused)) static gauge_t usage_global_ratio(usage_t u, state_t state) {
+  gauge_t global_rate =
+      usage_global_rate(u, STATE_ACTIVE) + usage_global_rate(u, STATE_IDLE);
+  return usage_global_rate(u, state) / global_rate;
+}
+
 /* Takes the zero-index number of a CPU and makes sure that the module-global
  * cpu_states buffer is large enough. Returne ENOMEM on erorr. */
 static int cpu_states_alloc(size_t cpu_num) /* {{{ */
index cb1f83b316850f1fcaaf3e1abc16b55d949ce086..08fe87019d498bd4f77475de42d23b1dc76d271b 100644 (file)
@@ -190,11 +190,61 @@ DEF_TEST(usage_global_rate) {
   return 0;
 }
 
+DEF_TEST(usage_global_ratio) {
+  usage_t usage = {0};
+
+  cdtime_t t0 = TIME_T_TO_CDTIME_T(100);
+  usage_init(&usage, t0);
+  for (size_t cpu = 0; cpu < 4; cpu++) {
+    for (state_t s = 0; s < STATE_ACTIVE; s++) {
+      usage_record(&usage, cpu, s, 1000);
+    }
+  }
+
+  cdtime_t t1 = t0 + TIME_T_TO_CDTIME_T(10);
+  usage_init(&usage, t1);
+  derive_t global_increment = 0;
+  for (size_t cpu = 0; cpu < 4; cpu++) {
+    for (state_t s = 0; s < STATE_ACTIVE; s++) {
+      derive_t increment = ((derive_t)cpu * STATE_ACTIVE) + ((derive_t)s);
+      global_increment += increment;
+      usage_record(&usage, cpu, s, 1000 + increment);
+    }
+  }
+
+  derive_t global_active_increment = 0;
+  for (state_t s = 0; s < STATE_ACTIVE; s++) {
+    derive_t state_increment = 0;
+    for (size_t cpu = 0; cpu < 4; cpu++) {
+      derive_t increment = ((derive_t)cpu * STATE_ACTIVE) + ((derive_t)s);
+      state_increment += increment;
+    }
+    gauge_t want_state_ratio =
+        ((gauge_t)state_increment) / ((gauge_t)global_increment);
+    EXPECT_EQ_DOUBLE(want_state_ratio, usage_global_ratio(usage, s));
+
+    if (s != STATE_IDLE) {
+      global_active_increment += state_increment;
+    }
+  }
+  gauge_t want_global_active_ratio =
+      ((gauge_t)global_active_increment) / ((gauge_t)global_increment);
+  EXPECT_EQ_DOUBLE(want_global_active_ratio,
+                   usage_global_ratio(usage, STATE_ACTIVE));
+
+  EXPECT_EQ_DOUBLE(1.0 - want_global_active_ratio,
+                   usage_global_ratio(usage, STATE_IDLE));
+
+  usage_reset(&usage);
+  return 0;
+}
+
 int main(void) {
   RUN_TEST(usage_rate);
   RUN_TEST(usage_ratio);
   RUN_TEST(usage_active_rate);
   RUN_TEST(usage_global_rate);
+  RUN_TEST(usage_global_ratio);
 
   END_TEST;
 }