[PATCH v1 1/2] libperf threadmap: Add ability to find index from pid

From: Ian Rogers
Date: Sat Jul 20 2024 - 03:46:59 EST


It is useful to be able to determine the index of thread in a thread
map as the index is used in other situations like finding the perf
count values. Unlike with perf_cpu_map__idx a binary search can't be
performed as the array isn't ordered. Also -1 in the array matches any
pid.

Signed-off-by: Ian Rogers <irogers@xxxxxxxxxx>
---
tools/lib/perf/include/internal/threadmap.h | 1 +
tools/lib/perf/threadmap.c | 9 +++++++++
2 files changed, 10 insertions(+)

diff --git a/tools/lib/perf/include/internal/threadmap.h b/tools/lib/perf/include/internal/threadmap.h
index df748baf9eda..92889d81b6b1 100644
--- a/tools/lib/perf/include/internal/threadmap.h
+++ b/tools/lib/perf/include/internal/threadmap.h
@@ -19,5 +19,6 @@ struct perf_thread_map {
};

struct perf_thread_map *perf_thread_map__realloc(struct perf_thread_map *map, int nr);
+int perf_thread_map__idx(const struct perf_thread_map *threads, pid_t pid);

#endif /* __LIBPERF_INTERNAL_THREADMAP_H */
diff --git a/tools/lib/perf/threadmap.c b/tools/lib/perf/threadmap.c
index 07968f3ea093..728683199a85 100644
--- a/tools/lib/perf/threadmap.c
+++ b/tools/lib/perf/threadmap.c
@@ -99,3 +99,12 @@ pid_t perf_thread_map__pid(struct perf_thread_map *map, int idx)
{
return map->map[idx].pid;
}
+
+int perf_thread_map__idx(const struct perf_thread_map *threads, pid_t pid)
+{
+ for (int i = 0; i < threads->nr; i++) {
+ if (pid == threads->map[i].pid || threads->map[i].pid == -1)
+ return i;
+ }
+ return -1;
+}
--
2.45.2.1089.g2a221341d9-goog