]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
cgtop: use dynamic width for CPU% column (#43286) main
authorKakueeen <liuzhangjian@uniontech.com>
Mon, 10 Aug 2026 15:38:17 +0000 (23:38 +0800)
committerGitHub <noreply@github.com>
Mon, 10 Aug 2026 15:38:17 +0000 (00:38 +0900)
On many-CPU hosts, the CPU% column in systemd-cgtop can exceed the
hardcoded %6.1f format width (e.g. 12769.4% on a 128-CPU host),
causing column overflow and table misalignment.

Follow the existing maxtcpu pattern for CPU Time: dynamically compute
the maximum width of CPU percentage values and use it for both the
header and data rows.

Fixes #39819

src/cgtop/cgtop.c

index 0c96ad7891a7831f6fac584cff3e99ff1996fffb..974a946142a2fd94dc1a150cee1ec2c4649c8a6e 100644 (file)
@@ -7,6 +7,7 @@
 #include "build.h"
 #include "cgroup-show.h"
 #include "cgroup-util.h"
+#include "cpu-set-util.h"
 #include "fd-util.h"
 #include "fileio.h"
 #include "format-table.h"
@@ -581,7 +582,8 @@ static void display(Hashmap *a) {
         Group *g;
         Group **array;
         signed path_columns;
-        unsigned rows, n = 0, maxtcpu = 0, maxtpath = 3; /* 3 for ellipsize() to work properly */
+        unsigned rows, n = 0, maxtcpu = 0, maxtpath = 3, /* 3 for ellipsize() to work properly */
+                maxpcpu = 6; /* minimum width for "%CPU" header */
 
         assert(a);
 
@@ -604,13 +606,19 @@ static void display(Hashmap *a) {
                                strlen(array[j]->path));
         }
 
+        if (arg_cpu_type == CPU_PERCENTAGE) {
+                unsigned n_cpus;
+                if (cpus_online(&n_cpus) >= 0)
+                        maxpcpu = MAX(maxpcpu, DECIMAL_STR_WIDTH(n_cpus) + STRLEN("00.0"));
+        }
+
         rows = lines();
         if (rows <= 10)
                 rows = 10;
 
         if (on_tty()) {
                 const char *on, *off;
-                int cpu_len = arg_cpu_type == CPU_PERCENTAGE ? 6 : maxtcpu;
+                int cpu_len = arg_cpu_type == CPU_PERCENTAGE ? (int) maxpcpu : (int) maxtcpu;
 
                 path_columns = columns() - 36 - cpu_len;
                 if (path_columns < 10)
@@ -660,9 +668,9 @@ static void display(Hashmap *a) {
 
                 if (arg_cpu_type == CPU_PERCENTAGE) {
                         if (g->cpu_valid)
-                                printf(" %6.1f", g->cpu_fraction*100);
+                                printf(" %*.1f", (int) maxpcpu, g->cpu_fraction*100);
                         else
-                                fputs("      -", stdout);
+                                printf(" %*s", (int) maxpcpu, "-");
                 } else
                         printf(" %*s",
                                (int) maxtcpu,