OSDN Git Service

libperf cpumap: Use binary search in perf_cpu_map__idx() as array are sorted
authorRiccardo Mancini <rickyman7@gmail.com>
Sat, 21 Aug 2021 09:19:07 +0000 (11:19 +0200)
committerArnaldo Carvalho de Melo <acme@redhat.com>
Fri, 8 Oct 2021 14:29:16 +0000 (11:29 -0300)
Since 7074674e7338863e ("perf cpumap: Maintain cpumaps ordered and
without dups") perf_cpu_map elements are sorted in ascending order.

This patch improves perf_cpu_map__idx() by using a binary search.

Signed-off-by: Riccardo Mancini <rickyman7@gmail.com>
Cc: Andi Kleen <ak@linux.intel.com>
Cc: Ian Rogers <irogers@google.com>
Cc: Jiri Olsa <jolsa@redhat.com>
Cc: Mark Rutland <mark.rutland@arm.com>
Cc: Namhyung Kim <namhyung@kernel.org>
Cc: Peter Zijlstra <peterz@infradead.org>
Link: http://lore.kernel.org/lkml/f1543c15797169c21e8b205a4a6751159180580d.1629490974.git.rickyman7@gmail.com
[ Removed 'else' after if + return, declared variables where needed ]
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
tools/lib/perf/cpumap.c

index 6d8e521..adaad3d 100644 (file)
@@ -270,11 +270,19 @@ bool perf_cpu_map__empty(const struct perf_cpu_map *map)
 
 int perf_cpu_map__idx(struct perf_cpu_map *cpus, int cpu)
 {
-       int i;
+       int low = 0, high = cpus->nr;
 
-       for (i = 0; i < cpus->nr; ++i) {
-               if (cpus->map[i] == cpu)
-                       return i;
+       while (low < high) {
+               int idx = (low + high) / 2,
+                   cpu_at_idx = cpus->map[idx];
+
+               if (cpu_at_idx == cpu)
+                       return idx;
+
+               if (cpu_at_idx > cpu)
+                       high = idx;
+               else
+                       low = idx + 1;
        }
 
        return -1;