util/cutils: Introduce freq_to_str() to display Hertz units
authorPhilippe Mathieu-Daudé <f4bug@amsat.org>
Mon, 12 Oct 2020 09:57:44 +0000 (11:57 +0200)
committerPhilippe Mathieu-Daudé <f4bug@amsat.org>
Fri, 16 Oct 2020 16:58:10 +0000 (18:58 +0200)
Introduce freq_to_str() to convert frequency values in human
friendly units using the SI units for Hertz.

Suggested-by: Luc Michel <luc@lmichel.fr>
Signed-off-by: Philippe Mathieu-Daudé <f4bug@amsat.org>
Reviewed-by: Alistair Francis <alistair.francis@wdc.com>
Reviewed-by: Luc Michel <luc@lmichel.fr>
Message-Id: <20201012095804.3335117-2-f4bug@amsat.org>

include/qemu/cutils.h
util/cutils.c

index 3a86ec0321e812d8535d6ad028a7251586d4ef5f..4bbf4834ea5c98440fa9322ce889ec03c9cadeb0 100644 (file)
@@ -158,6 +158,18 @@ int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result);
 
 char *size_to_str(uint64_t val);
 
+/**
+ * freq_to_str:
+ * @freq_hz: frequency to stringify
+ *
+ * Return human readable string for frequency @freq_hz.
+ * Use SI units like KHz, MHz, and so forth.
+ *
+ * The caller is responsible for releasing the value returned
+ * with g_free() after use.
+ */
+char *freq_to_str(uint64_t freq_hz);
+
 /* used to print char* safely */
 #define STR_OR_NULL(str) ((str) ? (str) : "null")
 
index 8da34e04b0b404543d97b5437bbc83709d963b31..be4e43a9eff2b26b875c7117b9cec320328265e1 100644 (file)
@@ -885,6 +885,20 @@ char *size_to_str(uint64_t val)
     return g_strdup_printf("%0.3g %sB", (double)val / div, suffixes[i]);
 }
 
+char *freq_to_str(uint64_t freq_hz)
+{
+    static const char *const suffixes[] = { "", "K", "M", "G", "T", "P", "E" };
+    double freq = freq_hz;
+    size_t idx = 0;
+
+    while (freq >= 1000.0 && idx < ARRAY_SIZE(suffixes)) {
+        freq /= 1000.0;
+        idx++;
+    }
+
+    return g_strdup_printf("%0.3g %sHz", freq, suffixes[idx]);
+}
+
 int qemu_pstrcmp0(const char **str1, const char **str2)
 {
     return g_strcmp0(*str1, *str2);