1#!/usr/bin/env python3 2# SPDX-License-Identifier: GPL-2.0-only 3# 4# Copyright (C) 2024 Red Hat, Inc. Daniel Bristot de Oliveira <bristot@kernel.org> 5# 6# This is a sample code about how to use timerlat's timer by any workload 7# so rtla can measure and provide auto-analysis for the overall latency (IOW 8# the response time) for a task. 9# 10# Before running it, you need to dispatch timerlat with -U option in a terminal. 11# Then # run this script pinned to a CPU on another terminal. For example: 12# 13# timerlat_load.py 1 -p 95 14# 15# The "Timerlat IRQ" is the IRQ latency, The thread latency is the latency 16# for the python process to get the CPU. The Ret from user Timer Latency is 17# the overall latency. In other words, it is the response time for that 18# activation. 19# 20# This is just an example, the load is reading 20MB of data from /dev/full 21# It is in python because it is easy to read :-) 22 23import argparse 24import sys 25import os 26 27parser = argparse.ArgumentParser(description='user-space timerlat thread in Python') 28parser.add_argument("cpu", type=int, help='CPU to run timerlat thread') 29parser.add_argument("-p", "--prio", type=int, help='FIFO priority') 30args = parser.parse_args() 31 32try: 33 affinity_mask = {args.cpu} 34 os.sched_setaffinity(0, affinity_mask) 35except Exception as e: 36 print(f"Error setting affinity: {e}") 37 sys.exit(1) 38 39if args.prio: 40 try: 41 param = os.sched_param(args.prio) 42 os.sched_setscheduler(0, os.SCHED_FIFO, param) 43 except Exception as e: 44 print(f"Error setting priority: {e}") 45 sys.exit(1) 46 47try: 48 timerlat_path = f"/sys/kernel/tracing/osnoise/per_cpu/cpu{args.cpu}/timerlat_fd" 49 timerlat_fd = open(timerlat_path, 'r') 50except PermissionError: 51 print("Permission denied. Please check your access rights.") 52 sys.exit(1) 53except OSError: 54 print("Error opening timerlat fd, did you run timerlat -U?") 55 sys.exit(1) 56 57try: 58 data_fd = open("/dev/full", 'r') 59except Exception as e: 60 print(f"Error opening data fd: {e}") 61 sys.exit(1) 62 63while True: 64 try: 65 timerlat_fd.read(1) 66 data_fd.read(20 * 1024 * 1024) 67 except KeyboardInterrupt: 68 print("Leaving") 69 break 70 except IOError as e: 71 print(f"I/O error occurred: {e}") 72 break 73 except Exception as e: 74 print(f"Unexpected error: {e}") 75 break 76 77timerlat_fd.close() 78data_fd.close() 79