7from datetime
import datetime
37EXCLUDE_KEYWORDS = {
"code",
"chrome",
"firefox",
"vscode",
"gnome"}
41 parser = argparse.ArgumentParser(description=
"Monitor CPU usage of ROS2 nodes")
45 default=
"carma-cpu-usage-logs",
46 help=
"Directory to store output files (default: carma-cpu-usage-logs)",
51 help=
"Additional comma-separated patterns to include in process filtering",
53 return parser.parse_args()
57 if not os.path.exists(output_dir):
58 os.makedirs(output_dir)
59 timestamp = datetime.now().strftime(
"%Y_%m_%d-%H_%M_%S")
60 filename = f
"cpu_usage_ros2_nodes_{timestamp}.csv"
61 return os.path.join(output_dir, filename)
66 Check if a process
is ROS-related based on name
and command line
69 name_lower = proc_info[
"name"].lower()
70 cmdline_lower = cmdline.lower()
73 if any(excl
in name_lower
or excl
in cmdline_lower
for excl
in EXCLUDE_KEYWORDS):
78 keyword
in name_lower
or keyword
in cmdline_lower
for keyword
in ROS_KEYWORDS
84 Try to get ROS-related environment variables for a process
87 proc = psutil.Process(pid)
89 ros_env = {k: v
for k, v
in env.items()
if "ROS" in k}
91 except (psutil.NoSuchProcess, psutil.AccessDenied):
99 if args.include_pattern:
100 additional_patterns = set(args.include_pattern.split(
","))
101 ROS_KEYWORDS.update(additional_patterns)
105 with open(output_file, mode=
"a")
as file:
106 writer = csv.writer(file)
122 print(f
"Starting to monitor the CPU usage data and saving to: {output_file}")
125 total_memory_gb = psutil.virtual_memory().total / (1024**3)
126 total_cpus = os.cpu_count()
129 timestamp = datetime.now().strftime(
"%Y-%m-%d %H:%M:%S.%f")[:-3]
130 total_cpu_percent = psutil.cpu_percent(interval=
None)
131 total_memory_percent = (
132 psutil.virtual_memory().percent
135 for proc
in psutil.process_iter(
136 [
"pid",
"name",
"cpu_percent",
"memory_percent",
"cmdline"]
140 " ".join(proc.info[
"cmdline"])
if proc.info[
"cmdline"]
else ""
144 pid = proc.info[
"pid"]
145 name = proc.info[
"name"]
146 cpu_percent = proc.info[
"cpu_percent"]
147 memory_percent = proc.info[
"memory_percent"]
159 total_memory_percent,
165 psutil.NoSuchProcess,
167 psutil.ZombieProcess,
174if __name__ ==
"__main__":
def is_ros_related_process(proc_info, cmdline)
def get_process_environment(pid)
def setup_logging_directory(output_dir)