[PATCH v2] rt-tests: hwlatdetect: Add --time-format argument

Costa Shulyupin <[email protected]> Sun, 26 Apr 2026 17:01:15 +0300
Newsgroups org.kernel.vger.linux-rt-users
Message-ID <[email protected]>
Add --time-format argument to customize timestamp output format using
strftime directives. By default raw timestamps are output for backward
compatibility.

Add %n directive processing for nanoseconds (9 digits) since strftime
doesn't support it.

Truncate nanoseconds to 6 digits before float conversion to avoid
rounding collision.

Signed-off-by: Costa Shulyupin <[email protected]>

---
v2:
- Use global args instead of class variable for time_format
Address John Kacur's review comments:
- Handle timestamps without decimal point in format_timestamp()
- Refactor time_format
- Fix misleading docstring about float precision
---
 src/hwlatdetect/hwlatdetect.py | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)

diff --git a/src/hwlatdetect/hwlatdetect.py b/src/hwlatdetect/hwlatdetect.py
index 18ca930487f0..ee1e0171210d 100755
--- a/src/hwlatdetect/hwlatdetect.py
+++ b/src/hwlatdetect/hwlatdetect.py
@@ -14,11 +14,13 @@
 import subprocess
 import sys
 import time
+from datetime import datetime
 
 version = "0.8"
 debugging = False
 quiet = False
 watch = False
+args = None
 
 
 def debug(dstr):
@@ -284,8 +286,18 @@         def __init__(self, line):
             self.outer = int(o)
             self.count = int(kv["count"]) if "count" in kv else None
 
+        def format_timestamp(self):
+            """Format timestamp with %n (nanoseconds) support."""
+            if not args.time_format:
+                return self.timestamp
+            p = self.timestamp.split('.')
+            ns = p[1] if len(p) > 1 else '0' * 9
+            t = datetime.fromtimestamp(float(f"{p[0]}.{ns[:6]}"))
+            return t.strftime(args.time_format.replace('%n', ns))
+
         def __str__(self):
-            s = f"ts: {self.timestamp}, delta:{self.delta:.6f}, inner:{self.inner}, outer:{self.outer}, cpu:{self.cpu}"
+            s = f"ts: {self.format_timestamp()}"
+            s += f", delta:{self.delta:.6f}, inner:{self.inner}, outer:{self.outer}, cpu:{self.cpu}"
             return s if self.count is None else s + f", count:{self.count}"
 
         def display(self):
@@ -472,6 +484,9 @@     def cleanup(self):
                         dest="watch",
                         help="print sample data to stdout as it arrives")
 
+    parser.add_argument("--time-format",
+                        help="strftime format for timestamps (e.g. %%H:%%M:%%S.%%n)")
+
     args = parser.parse_args()
 
     # need these before creating detector instance
-- 
2.53.0