4 * Builtin stat command: Give a precise performance counters summary
5 * overview about any workload, CPU or specific PID.
9 $ perf stat ./hackbench 10
13 Performance counter stats for './hackbench 10':
15 1708.761321 task-clock # 11.037 CPUs utilized
16 41,190 context-switches # 0.024 M/sec
17 6,735 CPU-migrations # 0.004 M/sec
18 17,318 page-faults # 0.010 M/sec
19 5,205,202,243 cycles # 3.046 GHz
20 3,856,436,920 stalled-cycles-frontend # 74.09% frontend cycles idle
21 1,600,790,871 stalled-cycles-backend # 30.75% backend cycles idle
22 2,603,501,247 instructions # 0.50 insns per cycle
23 # 1.48 stalled cycles per insn
24 484,357,498 branches # 283.455 M/sec
25 6,388,934 branch-misses # 1.32% of all branches
27 0.154822978 seconds time elapsed
30 * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
32 * Improvements and fixes by:
34 * Arjan van de Ven <arjan@linux.intel.com>
35 * Yanmin Zhang <yanmin.zhang@intel.com>
36 * Wu Fengguang <fengguang.wu@intel.com>
37 * Mike Galbraith <efault@gmx.de>
38 * Paul Mackerras <paulus@samba.org>
39 * Jaswinder Singh Rajput <jaswinder@kernel.org>
41 * Released under the GPL v2. (and only v2, not any later version)
46 #include "util/cgroup.h"
47 #include "util/util.h"
48 #include "util/parse-options.h"
49 #include "util/parse-events.h"
51 #include "util/event.h"
52 #include "util/evlist.h"
53 #include "util/evsel.h"
54 #include "util/debug.h"
55 #include "util/color.h"
56 #include "util/stat.h"
57 #include "util/header.h"
58 #include "util/cpumap.h"
59 #include "util/thread.h"
60 #include "util/thread_map.h"
63 #include <sys/prctl.h>
66 #define DEFAULT_SEPARATOR " "
67 #define CNTR_NOT_SUPPORTED "<not supported>"
68 #define CNTR_NOT_COUNTED "<not counted>"
70 static void print_stat(int argc, const char **argv);
71 static void print_counter_aggr(struct perf_evsel *counter, char *prefix);
72 static void print_counter(struct perf_evsel *counter, char *prefix);
73 static void print_aggr(char *prefix);
75 /* Default events used for perf stat -T */
76 static const char *transaction_attrs = {
88 /* More limited version when the CPU does not have all events. */
89 static const char * transaction_limited_attrs = {
99 static struct perf_evlist *evsel_list;
101 static struct target target = {
105 static int run_count = 1;
106 static bool no_inherit = false;
107 static bool scale = true;
108 static enum aggr_mode aggr_mode = AGGR_GLOBAL;
109 static volatile pid_t child_pid = -1;
110 static bool null_run = false;
111 static int detailed_run = 0;
112 static bool transaction_run;
113 static bool big_num = true;
114 static int big_num_opt = -1;
115 static const char *csv_sep = NULL;
116 static bool csv_output = false;
117 static bool group = false;
118 static FILE *output = NULL;
119 static const char *pre_cmd = NULL;
120 static const char *post_cmd = NULL;
121 static bool sync_run = false;
122 static unsigned int interval = 0;
123 static unsigned int initial_delay = 0;
124 static unsigned int unit_width = 4; /* strlen("unit") */
125 static bool forever = false;
126 static struct timespec ref_time;
127 static struct cpu_map *aggr_map;
128 static int (*aggr_get_id)(struct cpu_map *m, int cpu);
130 static volatile int done = 0;
132 static inline void diff_timespec(struct timespec *r, struct timespec *a,
135 r->tv_sec = a->tv_sec - b->tv_sec;
136 if (a->tv_nsec < b->tv_nsec) {
137 r->tv_nsec = a->tv_nsec + 1000000000L - b->tv_nsec;
140 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
144 static inline struct cpu_map *perf_evsel__cpus(struct perf_evsel *evsel)
146 return (evsel->cpus && !target.cpu_list) ? evsel->cpus : evsel_list->cpus;
149 static inline int perf_evsel__nr_cpus(struct perf_evsel *evsel)
151 return perf_evsel__cpus(evsel)->nr;
154 static void perf_evsel__reset_stat_priv(struct perf_evsel *evsel)
157 struct perf_stat *ps = evsel->priv;
159 for (i = 0; i < 3; i++)
160 init_stats(&ps->res_stats[i]);
162 perf_stat_evsel_id_init(evsel);
165 static int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel)
167 evsel->priv = zalloc(sizeof(struct perf_stat));
168 if (evsel->priv == NULL)
170 perf_evsel__reset_stat_priv(evsel);
174 static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
179 static int perf_evsel__alloc_prev_raw_counts(struct perf_evsel *evsel)
184 sz = sizeof(*evsel->counts) +
185 (perf_evsel__nr_cpus(evsel) * sizeof(struct perf_counts_values));
191 evsel->prev_raw_counts = addr;
196 static void perf_evsel__free_prev_raw_counts(struct perf_evsel *evsel)
198 zfree(&evsel->prev_raw_counts);
201 static void perf_evlist__free_stats(struct perf_evlist *evlist)
203 struct perf_evsel *evsel;
205 evlist__for_each(evlist, evsel) {
206 perf_evsel__free_stat_priv(evsel);
207 perf_evsel__free_counts(evsel);
208 perf_evsel__free_prev_raw_counts(evsel);
212 static int perf_evlist__alloc_stats(struct perf_evlist *evlist, bool alloc_raw)
214 struct perf_evsel *evsel;
216 evlist__for_each(evlist, evsel) {
217 if (perf_evsel__alloc_stat_priv(evsel) < 0 ||
218 perf_evsel__alloc_counts(evsel, perf_evsel__nr_cpus(evsel)) < 0 ||
219 (alloc_raw && perf_evsel__alloc_prev_raw_counts(evsel) < 0))
226 perf_evlist__free_stats(evlist);
230 static void perf_stat__reset_stats(struct perf_evlist *evlist)
232 struct perf_evsel *evsel;
234 evlist__for_each(evlist, evsel) {
235 perf_evsel__reset_stat_priv(evsel);
236 perf_evsel__reset_counts(evsel, perf_evsel__nr_cpus(evsel));
239 perf_stat__reset_shadow_stats();
242 static int create_perf_stat_counter(struct perf_evsel *evsel)
244 struct perf_event_attr *attr = &evsel->attr;
247 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
248 PERF_FORMAT_TOTAL_TIME_RUNNING;
250 attr->inherit = !no_inherit;
252 if (target__has_cpu(&target))
253 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel));
255 if (!target__has_task(&target) && perf_evsel__is_group_leader(evsel)) {
258 attr->enable_on_exec = 1;
261 return perf_evsel__open_per_thread(evsel, evsel_list->threads);
265 * Does the counter have nsecs as a unit?
267 static inline int nsec_counter(struct perf_evsel *evsel)
269 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
270 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
276 static void zero_per_pkg(struct perf_evsel *counter)
278 if (counter->per_pkg_mask)
279 memset(counter->per_pkg_mask, 0, MAX_NR_CPUS);
282 static int check_per_pkg(struct perf_evsel *counter, int cpu, bool *skip)
284 unsigned long *mask = counter->per_pkg_mask;
285 struct cpu_map *cpus = perf_evsel__cpus(counter);
290 if (!counter->per_pkg)
293 if (cpu_map__empty(cpus))
297 mask = zalloc(MAX_NR_CPUS);
301 counter->per_pkg_mask = mask;
304 s = cpu_map__get_socket(cpus, cpu);
308 *skip = test_and_set_bit(s, mask) == 1;
312 static int read_cb(struct perf_evsel *evsel, int cpu, int thread __maybe_unused,
313 struct perf_counts_values *count)
315 struct perf_counts_values *aggr = &evsel->counts->aggr;
316 static struct perf_counts_values zero;
319 if (check_per_pkg(evsel, cpu, &skip)) {
320 pr_err("failed to read per-pkg counter\n");
331 if (!evsel->snapshot)
332 perf_evsel__compute_deltas(evsel, cpu, count);
333 perf_counts_values__scale(count, scale, NULL);
334 evsel->counts->cpu[cpu] = *count;
335 if (aggr_mode == AGGR_NONE)
336 perf_stat__update_shadow_stats(evsel, count->values, cpu);
339 aggr->val += count->val;
341 aggr->ena += count->ena;
342 aggr->run += count->run;
351 static int read_counter(struct perf_evsel *counter);
354 * Read out the results of a single counter:
355 * aggregate counts across CPUs in system-wide mode
357 static int read_counter_aggr(struct perf_evsel *counter)
359 struct perf_counts_values *aggr = &counter->counts->aggr;
360 struct perf_stat *ps = counter->priv;
361 u64 *count = counter->counts->aggr.values;
364 aggr->val = aggr->ena = aggr->run = 0;
366 if (read_counter(counter))
369 if (!counter->snapshot)
370 perf_evsel__compute_deltas(counter, -1, aggr);
371 perf_counts_values__scale(aggr, scale, &counter->counts->scaled);
373 for (i = 0; i < 3; i++)
374 update_stats(&ps->res_stats[i], count[i]);
377 fprintf(output, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
378 perf_evsel__name(counter), count[0], count[1], count[2]);
382 * Save the full runtime - to allow normalization during printout:
384 perf_stat__update_shadow_stats(counter, count, 0);
390 * Read out the results of a single counter:
391 * do not aggregate counts across CPUs in system-wide mode
393 static int read_counter(struct perf_evsel *counter)
395 int nthreads = thread_map__nr(evsel_list->threads);
396 int ncpus = perf_evsel__nr_cpus(counter);
399 if (!counter->supported)
402 if (counter->system_wide)
405 if (counter->per_pkg)
406 zero_per_pkg(counter);
408 for (thread = 0; thread < nthreads; thread++) {
409 for (cpu = 0; cpu < ncpus; cpu++) {
410 if (perf_evsel__read_cb(counter, cpu, thread, read_cb))
418 static void print_interval(void)
420 static int num_print_interval;
421 struct perf_evsel *counter;
422 struct perf_stat *ps;
423 struct timespec ts, rs;
426 if (aggr_mode == AGGR_GLOBAL) {
427 evlist__for_each(evsel_list, counter) {
429 memset(ps->res_stats, 0, sizeof(ps->res_stats));
430 read_counter_aggr(counter);
433 evlist__for_each(evsel_list, counter) {
435 memset(ps->res_stats, 0, sizeof(ps->res_stats));
436 read_counter(counter);
440 clock_gettime(CLOCK_MONOTONIC, &ts);
441 diff_timespec(&rs, &ts, &ref_time);
442 sprintf(prefix, "%6lu.%09lu%s", rs.tv_sec, rs.tv_nsec, csv_sep);
444 if (num_print_interval == 0 && !csv_output) {
447 fprintf(output, "# time socket cpus counts %*s events\n", unit_width, "unit");
450 fprintf(output, "# time core cpus counts %*s events\n", unit_width, "unit");
453 fprintf(output, "# time CPU counts %*s events\n", unit_width, "unit");
457 fprintf(output, "# time counts %*s events\n", unit_width, "unit");
461 if (++num_print_interval == 25)
462 num_print_interval = 0;
470 evlist__for_each(evsel_list, counter)
471 print_counter(counter, prefix);
475 evlist__for_each(evsel_list, counter)
476 print_counter_aggr(counter, prefix);
482 static void handle_initial_delay(void)
484 struct perf_evsel *counter;
487 const int ncpus = cpu_map__nr(evsel_list->cpus),
488 nthreads = thread_map__nr(evsel_list->threads);
490 usleep(initial_delay * 1000);
491 evlist__for_each(evsel_list, counter)
492 perf_evsel__enable(counter, ncpus, nthreads);
496 static volatile int workload_exec_errno;
499 * perf_evlist__prepare_workload will send a SIGUSR1
500 * if the fork fails, since we asked by setting its
501 * want_signal to true.
503 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
504 void *ucontext __maybe_unused)
506 workload_exec_errno = info->si_value.sival_int;
509 static int __run_perf_stat(int argc, const char **argv)
512 unsigned long long t0, t1;
513 struct perf_evsel *counter;
517 const bool forks = (argc > 0);
520 ts.tv_sec = interval / 1000;
521 ts.tv_nsec = (interval % 1000) * 1000000;
528 if (perf_evlist__prepare_workload(evsel_list, &target, argv, false,
529 workload_exec_failed_signal) < 0) {
530 perror("failed to prepare workload");
533 child_pid = evsel_list->workload.pid;
537 perf_evlist__set_leader(evsel_list);
539 evlist__for_each(evsel_list, counter) {
540 if (create_perf_stat_counter(counter) < 0) {
542 * PPC returns ENXIO for HW counters until 2.6.37
543 * (behavior changed with commit b0a873e).
545 if (errno == EINVAL || errno == ENOSYS ||
546 errno == ENOENT || errno == EOPNOTSUPP ||
549 ui__warning("%s event is not supported by the kernel.\n",
550 perf_evsel__name(counter));
551 counter->supported = false;
555 perf_evsel__open_strerror(counter, &target,
556 errno, msg, sizeof(msg));
557 ui__error("%s\n", msg);
560 kill(child_pid, SIGTERM);
564 counter->supported = true;
566 l = strlen(counter->unit);
571 if (perf_evlist__apply_filters(evsel_list, &counter)) {
572 error("failed to set filter \"%s\" on event %s with %d (%s)\n",
573 counter->filter, perf_evsel__name(counter), errno,
574 strerror_r(errno, msg, sizeof(msg)));
579 * Enable counters and exec the command:
582 clock_gettime(CLOCK_MONOTONIC, &ref_time);
585 perf_evlist__start_workload(evsel_list);
586 handle_initial_delay();
589 while (!waitpid(child_pid, &status, WNOHANG)) {
590 nanosleep(&ts, NULL);
596 if (workload_exec_errno) {
597 const char *emsg = strerror_r(workload_exec_errno, msg, sizeof(msg));
598 pr_err("Workload failed: %s\n", emsg);
602 if (WIFSIGNALED(status))
603 psignal(WTERMSIG(status), argv[0]);
605 handle_initial_delay();
607 nanosleep(&ts, NULL);
615 update_stats(&walltime_nsecs_stats, t1 - t0);
617 if (aggr_mode == AGGR_GLOBAL) {
618 evlist__for_each(evsel_list, counter) {
619 read_counter_aggr(counter);
620 perf_evsel__close_fd(counter, perf_evsel__nr_cpus(counter),
621 thread_map__nr(evsel_list->threads));
624 evlist__for_each(evsel_list, counter) {
625 read_counter(counter);
626 perf_evsel__close_fd(counter, perf_evsel__nr_cpus(counter), 1);
630 return WEXITSTATUS(status);
633 static int run_perf_stat(int argc, const char **argv)
638 ret = system(pre_cmd);
646 ret = __run_perf_stat(argc, argv);
651 ret = system(post_cmd);
659 static void print_running(u64 run, u64 ena)
662 fprintf(output, "%s%" PRIu64 "%s%.2f",
666 ena ? 100.0 * run / ena : 100.0);
667 } else if (run != ena) {
668 fprintf(output, " (%.2f%%)", 100.0 * run / ena);
672 static void print_noise_pct(double total, double avg)
674 double pct = rel_stddev_stats(total, avg);
677 fprintf(output, "%s%.2f%%", csv_sep, pct);
679 fprintf(output, " ( +-%6.2f%% )", pct);
682 static void print_noise(struct perf_evsel *evsel, double avg)
684 struct perf_stat *ps;
690 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
693 static void aggr_printout(struct perf_evsel *evsel, int id, int nr)
697 fprintf(output, "S%d-C%*d%s%*d%s",
698 cpu_map__id_to_socket(id),
700 cpu_map__id_to_cpu(id),
707 fprintf(output, "S%*d%s%*d%s",
716 fprintf(output, "CPU%*d%s",
718 perf_evsel__cpus(evsel)->map[id], csv_sep);
726 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg)
728 double msecs = avg / 1e6;
729 const char *fmt_v, *fmt_n;
732 fmt_v = csv_output ? "%.6f%s" : "%18.6f%s";
733 fmt_n = csv_output ? "%s" : "%-25s";
735 aggr_printout(evsel, id, nr);
737 scnprintf(name, sizeof(name), "%s%s",
738 perf_evsel__name(evsel), csv_output ? "" : " (msec)");
740 fprintf(output, fmt_v, msecs, csv_sep);
743 fprintf(output, "%s%s", evsel->unit, csv_sep);
745 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep);
747 fprintf(output, fmt_n, name);
750 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
752 if (csv_output || interval)
755 if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
756 fprintf(output, " # %8.3f CPUs utilized ",
757 avg / avg_stats(&walltime_nsecs_stats));
759 fprintf(output, " ");
762 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg)
764 double sc = evsel->scale;
766 int cpu = cpu_map__id_to_cpu(id);
769 fmt = sc != 1.0 ? "%.2f%s" : "%.0f%s";
772 fmt = sc != 1.0 ? "%'18.2f%s" : "%'18.0f%s";
774 fmt = sc != 1.0 ? "%18.2f%s" : "%18.0f%s";
777 aggr_printout(evsel, id, nr);
779 if (aggr_mode == AGGR_GLOBAL)
782 fprintf(output, fmt, avg, csv_sep);
785 fprintf(output, "%-*s%s",
786 csv_output ? 0 : unit_width,
787 evsel->unit, csv_sep);
789 fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel));
792 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name);
794 if (csv_output || interval)
797 perf_stat__print_shadow_stats(output, evsel, avg, cpu, aggr_mode);
800 static void print_aggr(char *prefix)
802 struct perf_evsel *counter;
803 int cpu, cpu2, s, s2, id, nr;
807 if (!(aggr_map || aggr_get_id))
810 for (s = 0; s < aggr_map->nr; s++) {
811 id = aggr_map->map[s];
812 evlist__for_each(evsel_list, counter) {
815 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
816 cpu2 = perf_evsel__cpus(counter)->map[cpu];
817 s2 = aggr_get_id(evsel_list->cpus, cpu2);
820 val += counter->counts->cpu[cpu].val;
821 ena += counter->counts->cpu[cpu].ena;
822 run += counter->counts->cpu[cpu].run;
826 fprintf(output, "%s", prefix);
828 if (run == 0 || ena == 0) {
829 aggr_printout(counter, id, nr);
831 fprintf(output, "%*s%s",
833 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
836 fprintf(output, "%-*s%s",
837 csv_output ? 0 : unit_width,
838 counter->unit, csv_sep);
840 fprintf(output, "%*s",
841 csv_output ? 0 : -25,
842 perf_evsel__name(counter));
845 fprintf(output, "%s%s",
846 csv_sep, counter->cgrp->name);
848 print_running(run, ena);
852 uval = val * counter->scale;
854 if (nsec_counter(counter))
855 nsec_printout(id, nr, counter, uval);
857 abs_printout(id, nr, counter, uval);
860 print_noise(counter, 1.0);
862 print_running(run, ena);
869 * Print out the results of a single counter:
870 * aggregated counts in system-wide mode
872 static void print_counter_aggr(struct perf_evsel *counter, char *prefix)
874 struct perf_stat *ps = counter->priv;
875 double avg = avg_stats(&ps->res_stats[0]);
876 int scaled = counter->counts->scaled;
878 double avg_enabled, avg_running;
880 avg_enabled = avg_stats(&ps->res_stats[1]);
881 avg_running = avg_stats(&ps->res_stats[2]);
884 fprintf(output, "%s", prefix);
886 if (scaled == -1 || !counter->supported) {
887 fprintf(output, "%*s%s",
889 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
891 fprintf(output, "%-*s%s",
892 csv_output ? 0 : unit_width,
893 counter->unit, csv_sep);
894 fprintf(output, "%*s",
895 csv_output ? 0 : -25,
896 perf_evsel__name(counter));
899 fprintf(output, "%s%s", csv_sep, counter->cgrp->name);
901 print_running(avg_running, avg_enabled);
906 uval = avg * counter->scale;
908 if (nsec_counter(counter))
909 nsec_printout(-1, 0, counter, uval);
911 abs_printout(-1, 0, counter, uval);
913 print_noise(counter, avg);
915 print_running(avg_running, avg_enabled);
916 fprintf(output, "\n");
920 * Print out the results of a single counter:
921 * does not use aggregated count in system-wide
923 static void print_counter(struct perf_evsel *counter, char *prefix)
929 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) {
930 val = counter->counts->cpu[cpu].val;
931 ena = counter->counts->cpu[cpu].ena;
932 run = counter->counts->cpu[cpu].run;
935 fprintf(output, "%s", prefix);
937 if (run == 0 || ena == 0) {
938 fprintf(output, "CPU%*d%s%*s%s",
940 perf_evsel__cpus(counter)->map[cpu], csv_sep,
942 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED,
945 fprintf(output, "%-*s%s",
946 csv_output ? 0 : unit_width,
947 counter->unit, csv_sep);
949 fprintf(output, "%*s",
950 csv_output ? 0 : -25,
951 perf_evsel__name(counter));
954 fprintf(output, "%s%s",
955 csv_sep, counter->cgrp->name);
957 print_running(run, ena);
962 uval = val * counter->scale;
964 if (nsec_counter(counter))
965 nsec_printout(cpu, 0, counter, uval);
967 abs_printout(cpu, 0, counter, uval);
970 print_noise(counter, 1.0);
971 print_running(run, ena);
977 static void print_stat(int argc, const char **argv)
979 struct perf_evsel *counter;
985 fprintf(output, "\n");
986 fprintf(output, " Performance counter stats for ");
987 if (target.system_wide)
988 fprintf(output, "\'system wide");
989 else if (target.cpu_list)
990 fprintf(output, "\'CPU(s) %s", target.cpu_list);
991 else if (!target__has_task(&target)) {
992 fprintf(output, "\'%s", argv[0]);
993 for (i = 1; i < argc; i++)
994 fprintf(output, " %s", argv[i]);
995 } else if (target.pid)
996 fprintf(output, "process id \'%s", target.pid);
998 fprintf(output, "thread id \'%s", target.tid);
1000 fprintf(output, "\'");
1002 fprintf(output, " (%d runs)", run_count);
1003 fprintf(output, ":\n\n");
1006 switch (aggr_mode) {
1012 evlist__for_each(evsel_list, counter)
1013 print_counter_aggr(counter, NULL);
1016 evlist__for_each(evsel_list, counter)
1017 print_counter(counter, NULL);
1025 fprintf(output, "\n");
1026 fprintf(output, " %17.9f seconds time elapsed",
1027 avg_stats(&walltime_nsecs_stats)/1e9);
1028 if (run_count > 1) {
1029 fprintf(output, " ");
1030 print_noise_pct(stddev_stats(&walltime_nsecs_stats),
1031 avg_stats(&walltime_nsecs_stats));
1033 fprintf(output, "\n\n");
1037 static volatile int signr = -1;
1039 static void skip_signal(int signo)
1041 if ((child_pid == -1) || interval)
1046 * render child_pid harmless
1047 * won't send SIGTERM to a random
1048 * process in case of race condition
1049 * and fast PID recycling
1054 static void sig_atexit(void)
1059 * avoid race condition with SIGCHLD handler
1060 * in skip_signal() which is modifying child_pid
1061 * goal is to avoid send SIGTERM to a random
1065 sigaddset(&set, SIGCHLD);
1066 sigprocmask(SIG_BLOCK, &set, &oset);
1068 if (child_pid != -1)
1069 kill(child_pid, SIGTERM);
1071 sigprocmask(SIG_SETMASK, &oset, NULL);
1076 signal(signr, SIG_DFL);
1077 kill(getpid(), signr);
1080 static int stat__set_big_num(const struct option *opt __maybe_unused,
1081 const char *s __maybe_unused, int unset)
1083 big_num_opt = unset ? 0 : 1;
1087 static int perf_stat_init_aggr_mode(void)
1089 switch (aggr_mode) {
1091 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) {
1092 perror("cannot build socket map");
1095 aggr_get_id = cpu_map__get_socket;
1098 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) {
1099 perror("cannot build core map");
1102 aggr_get_id = cpu_map__get_core;
1113 * Add default attributes, if there were no attributes specified or
1114 * if -d/--detailed, -d -d or -d -d -d is used:
1116 static int add_default_attributes(void)
1118 struct perf_event_attr default_attrs[] = {
1120 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
1121 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
1122 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
1123 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
1125 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
1126 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND },
1127 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND },
1128 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
1129 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
1130 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
1135 * Detailed stats (-d), covering the L1 and last level data caches:
1137 struct perf_event_attr detailed_attrs[] = {
1139 { .type = PERF_TYPE_HW_CACHE,
1141 PERF_COUNT_HW_CACHE_L1D << 0 |
1142 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1143 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1145 { .type = PERF_TYPE_HW_CACHE,
1147 PERF_COUNT_HW_CACHE_L1D << 0 |
1148 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1149 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1151 { .type = PERF_TYPE_HW_CACHE,
1153 PERF_COUNT_HW_CACHE_LL << 0 |
1154 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1155 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1157 { .type = PERF_TYPE_HW_CACHE,
1159 PERF_COUNT_HW_CACHE_LL << 0 |
1160 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1161 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1165 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches:
1167 struct perf_event_attr very_detailed_attrs[] = {
1169 { .type = PERF_TYPE_HW_CACHE,
1171 PERF_COUNT_HW_CACHE_L1I << 0 |
1172 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1173 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1175 { .type = PERF_TYPE_HW_CACHE,
1177 PERF_COUNT_HW_CACHE_L1I << 0 |
1178 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1179 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1181 { .type = PERF_TYPE_HW_CACHE,
1183 PERF_COUNT_HW_CACHE_DTLB << 0 |
1184 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1185 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1187 { .type = PERF_TYPE_HW_CACHE,
1189 PERF_COUNT_HW_CACHE_DTLB << 0 |
1190 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1191 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1193 { .type = PERF_TYPE_HW_CACHE,
1195 PERF_COUNT_HW_CACHE_ITLB << 0 |
1196 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1197 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1199 { .type = PERF_TYPE_HW_CACHE,
1201 PERF_COUNT_HW_CACHE_ITLB << 0 |
1202 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1203 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1208 * Very, very detailed stats (-d -d -d), adding prefetch events:
1210 struct perf_event_attr very_very_detailed_attrs[] = {
1212 { .type = PERF_TYPE_HW_CACHE,
1214 PERF_COUNT_HW_CACHE_L1D << 0 |
1215 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1216 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) },
1218 { .type = PERF_TYPE_HW_CACHE,
1220 PERF_COUNT_HW_CACHE_L1D << 0 |
1221 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) |
1222 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) },
1225 /* Set attrs if no event is selected and !null_run: */
1229 if (transaction_run) {
1231 if (pmu_have_event("cpu", "cycles-ct") &&
1232 pmu_have_event("cpu", "el-start"))
1233 err = parse_events(evsel_list, transaction_attrs, NULL);
1235 err = parse_events(evsel_list, transaction_limited_attrs, NULL);
1237 fprintf(stderr, "Cannot set up transaction events\n");
1243 if (!evsel_list->nr_entries) {
1244 if (perf_evlist__add_default_attrs(evsel_list, default_attrs) < 0)
1248 /* Detailed events get appended to the event list: */
1250 if (detailed_run < 1)
1253 /* Append detailed run extra attributes: */
1254 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0)
1257 if (detailed_run < 2)
1260 /* Append very detailed run extra attributes: */
1261 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0)
1264 if (detailed_run < 3)
1267 /* Append very, very detailed run extra attributes: */
1268 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs);
1271 int cmd_stat(int argc, const char **argv, const char *prefix __maybe_unused)
1273 bool append_file = false;
1275 const char *output_name = NULL;
1276 const struct option options[] = {
1277 OPT_BOOLEAN('T', "transaction", &transaction_run,
1278 "hardware transaction statistics"),
1279 OPT_CALLBACK('e', "event", &evsel_list, "event",
1280 "event selector. use 'perf list' to list available events",
1281 parse_events_option),
1282 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
1283 "event filter", parse_filter),
1284 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
1285 "child tasks do not inherit counters"),
1286 OPT_STRING('p', "pid", &target.pid, "pid",
1287 "stat events on existing process id"),
1288 OPT_STRING('t', "tid", &target.tid, "tid",
1289 "stat events on existing thread id"),
1290 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
1291 "system-wide collection from all CPUs"),
1292 OPT_BOOLEAN('g', "group", &group,
1293 "put the counters into a counter group"),
1294 OPT_BOOLEAN('c', "scale", &scale, "scale/normalize counters"),
1295 OPT_INCR('v', "verbose", &verbose,
1296 "be more verbose (show counter open errors, etc)"),
1297 OPT_INTEGER('r', "repeat", &run_count,
1298 "repeat command and print average + stddev (max: 100, forever: 0)"),
1299 OPT_BOOLEAN('n', "null", &null_run,
1300 "null run - dont start any counters"),
1301 OPT_INCR('d', "detailed", &detailed_run,
1302 "detailed run - start a lot of events"),
1303 OPT_BOOLEAN('S', "sync", &sync_run,
1304 "call sync() before starting a run"),
1305 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
1306 "print large numbers with thousands\' separators",
1308 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
1309 "list of cpus to monitor in system-wide"),
1310 OPT_SET_UINT('A', "no-aggr", &aggr_mode,
1311 "disable CPU count aggregation", AGGR_NONE),
1312 OPT_STRING('x', "field-separator", &csv_sep, "separator",
1313 "print counts with custom separator"),
1314 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
1315 "monitor event in cgroup name only", parse_cgroups),
1316 OPT_STRING('o', "output", &output_name, "file", "output file name"),
1317 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
1318 OPT_INTEGER(0, "log-fd", &output_fd,
1319 "log output to fd, instead of stderr"),
1320 OPT_STRING(0, "pre", &pre_cmd, "command",
1321 "command to run prior to the measured command"),
1322 OPT_STRING(0, "post", &post_cmd, "command",
1323 "command to run after to the measured command"),
1324 OPT_UINTEGER('I', "interval-print", &interval,
1325 "print counts at regular interval in ms (>= 100)"),
1326 OPT_SET_UINT(0, "per-socket", &aggr_mode,
1327 "aggregate counts per processor socket", AGGR_SOCKET),
1328 OPT_SET_UINT(0, "per-core", &aggr_mode,
1329 "aggregate counts per physical processor core", AGGR_CORE),
1330 OPT_UINTEGER('D', "delay", &initial_delay,
1331 "ms to wait before starting measurement after program start"),
1334 const char * const stat_usage[] = {
1335 "perf stat [<options>] [<command>]",
1338 int status = -EINVAL, run_idx;
1341 setlocale(LC_ALL, "");
1343 evsel_list = perf_evlist__new();
1344 if (evsel_list == NULL)
1347 argc = parse_options(argc, argv, options, stat_usage,
1348 PARSE_OPT_STOP_AT_NON_OPTION);
1351 if (output_name && strcmp(output_name, "-"))
1354 if (output_name && output_fd) {
1355 fprintf(stderr, "cannot use both --output and --log-fd\n");
1356 parse_options_usage(stat_usage, options, "o", 1);
1357 parse_options_usage(NULL, options, "log-fd", 0);
1361 if (output_fd < 0) {
1362 fprintf(stderr, "argument to --log-fd must be a > 0\n");
1363 parse_options_usage(stat_usage, options, "log-fd", 0);
1369 mode = append_file ? "a" : "w";
1371 output = fopen(output_name, mode);
1373 perror("failed to create output file");
1376 clock_gettime(CLOCK_REALTIME, &tm);
1377 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
1378 } else if (output_fd > 0) {
1379 mode = append_file ? "a" : "w";
1380 output = fdopen(output_fd, mode);
1382 perror("Failed opening logfd");
1389 if (!strcmp(csv_sep, "\\t"))
1392 csv_sep = DEFAULT_SEPARATOR;
1395 * let the spreadsheet do the pretty-printing
1398 /* User explicitly passed -B? */
1399 if (big_num_opt == 1) {
1400 fprintf(stderr, "-B option not supported with -x\n");
1401 parse_options_usage(stat_usage, options, "B", 1);
1402 parse_options_usage(NULL, options, "x", 1);
1404 } else /* Nope, so disable big number formatting */
1406 } else if (big_num_opt == 0) /* User passed --no-big-num */
1409 if (!argc && target__none(&target))
1410 usage_with_options(stat_usage, options);
1412 if (run_count < 0) {
1413 pr_err("Run count must be a positive number\n");
1414 parse_options_usage(stat_usage, options, "r", 1);
1416 } else if (run_count == 0) {
1421 /* no_aggr, cgroup are for system-wide only */
1422 if ((aggr_mode != AGGR_GLOBAL || nr_cgroups) &&
1423 !target__has_cpu(&target)) {
1424 fprintf(stderr, "both cgroup and no-aggregation "
1425 "modes only available in system-wide mode\n");
1427 parse_options_usage(stat_usage, options, "G", 1);
1428 parse_options_usage(NULL, options, "A", 1);
1429 parse_options_usage(NULL, options, "a", 1);
1433 if (add_default_attributes())
1436 target__validate(&target);
1438 if (perf_evlist__create_maps(evsel_list, &target) < 0) {
1439 if (target__has_task(&target)) {
1440 pr_err("Problems finding threads of monitor\n");
1441 parse_options_usage(stat_usage, options, "p", 1);
1442 parse_options_usage(NULL, options, "t", 1);
1443 } else if (target__has_cpu(&target)) {
1444 perror("failed to parse CPUs map");
1445 parse_options_usage(stat_usage, options, "C", 1);
1446 parse_options_usage(NULL, options, "a", 1);
1450 if (interval && interval < 100) {
1451 pr_err("print interval must be >= 100ms\n");
1452 parse_options_usage(stat_usage, options, "I", 1);
1456 if (perf_evlist__alloc_stats(evsel_list, interval))
1459 if (perf_stat_init_aggr_mode())
1463 * We dont want to block the signals - that would cause
1464 * child tasks to inherit that and Ctrl-C would not work.
1465 * What we want is for Ctrl-C to work in the exec()-ed
1466 * task, but being ignored by perf stat itself:
1470 signal(SIGINT, skip_signal);
1471 signal(SIGCHLD, skip_signal);
1472 signal(SIGALRM, skip_signal);
1473 signal(SIGABRT, skip_signal);
1476 for (run_idx = 0; forever || run_idx < run_count; run_idx++) {
1477 if (run_count != 1 && verbose)
1478 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
1481 status = run_perf_stat(argc, argv);
1482 if (forever && status != -1) {
1483 print_stat(argc, argv);
1484 perf_stat__reset_stats(evsel_list);
1488 if (!forever && status != -1 && !interval)
1489 print_stat(argc, argv);
1491 perf_evlist__free_stats(evsel_list);
1493 perf_evlist__delete(evsel_list);