4 * Builtin stat command: Give a precise performance counters summary
5 * overview about any workload, CPU or specific PID.
9 $ perf stat ~/hackbench 10
12 Performance counter stats for '/home/mingo/hackbench':
14 1255.538611 task clock ticks # 10.143 CPU utilization factor
15 54011 context switches # 0.043 M/sec
16 385 CPU migrations # 0.000 M/sec
17 17755 pagefaults # 0.014 M/sec
18 3808323185 CPU cycles # 3033.219 M/sec
19 1575111190 instructions # 1254.530 M/sec
20 17367895 cache references # 13.833 M/sec
21 7674421 cache misses # 6.112 M/sec
23 Wall-clock time elapsed: 123.786620 msecs
26 * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
28 * Improvements and fixes by:
30 * Arjan van de Ven <arjan@linux.intel.com>
31 * Yanmin Zhang <yanmin.zhang@intel.com>
32 * Wu Fengguang <fengguang.wu@intel.com>
33 * Mike Galbraith <efault@gmx.de>
34 * Paul Mackerras <paulus@samba.org>
35 * Jaswinder Singh Rajput <jaswinder@kernel.org>
37 * Released under the GPL v2. (and only v2, not any later version)
42 #include "util/util.h"
43 #include "util/parse-options.h"
44 #include "util/parse-events.h"
45 #include "util/event.h"
46 #include "util/evlist.h"
47 #include "util/evsel.h"
48 #include "util/debug.h"
49 #include "util/header.h"
50 #include "util/cpumap.h"
51 #include "util/thread.h"
52 #include "util/thread_map.h"
54 #include <sys/prctl.h>
58 #define DEFAULT_SEPARATOR " "
60 static struct perf_event_attr default_attrs[] = {
62 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
63 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
64 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
65 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
67 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
68 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES },
69 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
70 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
71 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
75 struct perf_evlist *evsel_list;
77 static bool system_wide = false;
78 static int run_idx = 0;
80 static int run_count = 1;
81 static bool no_inherit = false;
82 static bool scale = true;
83 static bool no_aggr = false;
84 static pid_t target_pid = -1;
85 static pid_t target_tid = -1;
86 static pid_t child_pid = -1;
87 static bool null_run = false;
88 static bool big_num = true;
89 static int big_num_opt = -1;
90 static const char *cpu_list;
91 static const char *csv_sep = NULL;
92 static bool csv_output = false;
94 static volatile int done = 0;
102 struct stats res_stats[3];
105 static int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel)
107 evsel->priv = zalloc(sizeof(struct perf_stat));
108 return evsel->priv == NULL ? -ENOMEM : 0;
111 static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
117 static void update_stats(struct stats *stats, u64 val)
122 delta = val - stats->mean;
123 stats->mean += delta / stats->n;
124 stats->M2 += delta*(val - stats->mean);
127 static double avg_stats(struct stats *stats)
133 * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
135 * (\Sum n_i^2) - ((\Sum n_i)^2)/n
136 * s^2 = -------------------------------
139 * http://en.wikipedia.org/wiki/Stddev
141 * The std dev of the mean is related to the std dev by:
148 static double stddev_stats(struct stats *stats)
150 double variance = stats->M2 / (stats->n - 1);
151 double variance_mean = variance / stats->n;
153 return sqrt(variance_mean);
156 struct stats runtime_nsecs_stats[MAX_NR_CPUS];
157 struct stats runtime_cycles_stats[MAX_NR_CPUS];
158 struct stats runtime_stalled_cycles_stats[MAX_NR_CPUS];
159 struct stats runtime_branches_stats[MAX_NR_CPUS];
160 struct stats runtime_cacherefs_stats[MAX_NR_CPUS];
161 struct stats walltime_nsecs_stats;
163 static int create_perf_stat_counter(struct perf_evsel *evsel)
165 struct perf_event_attr *attr = &evsel->attr;
168 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
169 PERF_FORMAT_TOTAL_TIME_RUNNING;
171 attr->inherit = !no_inherit;
174 return perf_evsel__open_per_cpu(evsel, evsel_list->cpus, false);
176 if (target_pid == -1 && target_tid == -1) {
178 attr->enable_on_exec = 1;
181 return perf_evsel__open_per_thread(evsel, evsel_list->threads, false);
185 * Does the counter have nsecs as a unit?
187 static inline int nsec_counter(struct perf_evsel *evsel)
189 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
190 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
197 * Update various tracking values we maintain to print
198 * more semantic information such as miss/hit ratios,
199 * instruction rates, etc:
201 static void update_shadow_stats(struct perf_evsel *counter, u64 *count)
203 if (perf_evsel__match(counter, SOFTWARE, SW_TASK_CLOCK))
204 update_stats(&runtime_nsecs_stats[0], count[0]);
205 else if (perf_evsel__match(counter, HARDWARE, HW_CPU_CYCLES))
206 update_stats(&runtime_cycles_stats[0], count[0]);
207 else if (perf_evsel__match(counter, HARDWARE, HW_STALLED_CYCLES))
208 update_stats(&runtime_stalled_cycles_stats[0], count[0]);
209 else if (perf_evsel__match(counter, HARDWARE, HW_BRANCH_INSTRUCTIONS))
210 update_stats(&runtime_branches_stats[0], count[0]);
211 else if (perf_evsel__match(counter, HARDWARE, HW_CACHE_REFERENCES))
212 update_stats(&runtime_cacherefs_stats[0], count[0]);
216 * Read out the results of a single counter:
217 * aggregate counts across CPUs in system-wide mode
219 static int read_counter_aggr(struct perf_evsel *counter)
221 struct perf_stat *ps = counter->priv;
222 u64 *count = counter->counts->aggr.values;
225 if (__perf_evsel__read(counter, evsel_list->cpus->nr,
226 evsel_list->threads->nr, scale) < 0)
229 for (i = 0; i < 3; i++)
230 update_stats(&ps->res_stats[i], count[i]);
233 fprintf(stderr, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
234 event_name(counter), count[0], count[1], count[2]);
238 * Save the full runtime - to allow normalization during printout:
240 update_shadow_stats(counter, count);
246 * Read out the results of a single counter:
247 * do not aggregate counts across CPUs in system-wide mode
249 static int read_counter(struct perf_evsel *counter)
254 for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
255 if (__perf_evsel__read_on_cpu(counter, cpu, 0, scale) < 0)
258 count = counter->counts->cpu[cpu].values;
260 update_shadow_stats(counter, count);
266 static int run_perf_stat(int argc __used, const char **argv)
268 unsigned long long t0, t1;
269 struct perf_evsel *counter;
271 int child_ready_pipe[2], go_pipe[2];
272 const bool forks = (argc > 0);
275 if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
276 perror("failed to create pipes");
281 if ((child_pid = fork()) < 0)
282 perror("failed to fork");
285 close(child_ready_pipe[0]);
287 fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
290 * Do a dummy execvp to get the PLT entry resolved,
291 * so we avoid the resolver overhead on the real
294 execvp("", (char **)argv);
297 * Tell the parent we're ready to go
299 close(child_ready_pipe[1]);
302 * Wait until the parent tells us to go.
304 if (read(go_pipe[0], &buf, 1) == -1)
305 perror("unable to read pipe");
307 execvp(argv[0], (char **)argv);
313 if (target_tid == -1 && target_pid == -1 && !system_wide)
314 evsel_list->threads->map[0] = child_pid;
317 * Wait for the child to be ready to exec.
319 close(child_ready_pipe[1]);
321 if (read(child_ready_pipe[0], &buf, 1) == -1)
322 perror("unable to read pipe");
323 close(child_ready_pipe[0]);
326 list_for_each_entry(counter, &evsel_list->entries, node) {
327 if (create_perf_stat_counter(counter) < 0) {
328 if (errno == -EPERM || errno == -EACCES) {
329 error("You may not have permission to collect %sstats.\n"
330 "\t Consider tweaking"
331 " /proc/sys/kernel/perf_event_paranoid or running as root.",
332 system_wide ? "system-wide " : "");
333 } else if (errno == ENOENT) {
334 error("%s event is not supported. ", event_name(counter));
336 error("open_counter returned with %d (%s). "
337 "/bin/dmesg may provide additional information.\n",
338 errno, strerror(errno));
341 kill(child_pid, SIGTERM);
342 die("Not all events could be opened.\n");
347 if (perf_evlist__set_filters(evsel_list)) {
348 error("failed to set filter with %d (%s)\n", errno,
354 * Enable counters and exec the command:
362 while(!done) sleep(1);
367 update_stats(&walltime_nsecs_stats, t1 - t0);
370 list_for_each_entry(counter, &evsel_list->entries, node) {
371 read_counter(counter);
372 perf_evsel__close_fd(counter, evsel_list->cpus->nr, 1);
375 list_for_each_entry(counter, &evsel_list->entries, node) {
376 read_counter_aggr(counter);
377 perf_evsel__close_fd(counter, evsel_list->cpus->nr,
378 evsel_list->threads->nr);
382 return WEXITSTATUS(status);
385 static void print_noise(struct perf_evsel *evsel, double avg)
387 struct perf_stat *ps;
393 fprintf(stderr, " ( +- %7.3f%% )",
394 100 * stddev_stats(&ps->res_stats[0]) / avg);
397 static void nsec_printout(int cpu, struct perf_evsel *evsel, double avg)
399 double msecs = avg / 1e6;
400 char cpustr[16] = { '\0', };
401 const char *fmt = csv_output ? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
404 sprintf(cpustr, "CPU%*d%s",
406 evsel_list->cpus->map[cpu], csv_sep);
408 fprintf(stderr, fmt, cpustr, msecs, csv_sep, event_name(evsel));
411 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
416 if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
417 fprintf(stderr, " # %8.3f CPUs utilized ", avg / avg_stats(&walltime_nsecs_stats));
420 static void abs_printout(int cpu, struct perf_evsel *evsel, double avg)
422 double total, ratio = 0.0;
423 char cpustr[16] = { '\0', };
429 fmt = "%s%'18.0f%s%-24s";
431 fmt = "%s%18.0f%s%-24s";
434 sprintf(cpustr, "CPU%*d%s",
436 evsel_list->cpus->map[cpu], csv_sep);
440 fprintf(stderr, fmt, cpustr, avg, csv_sep, event_name(evsel));
443 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
448 if (perf_evsel__match(evsel, HARDWARE, HW_INSTRUCTIONS)) {
449 total = avg_stats(&runtime_cycles_stats[cpu]);
454 fprintf(stderr, " # %4.2f insns per cycle", ratio);
456 total = avg_stats(&runtime_stalled_cycles_stats[cpu]);
460 fprintf(stderr, "\n # %4.2f stalled cycles per insn", ratio);
463 } else if (perf_evsel__match(evsel, HARDWARE, HW_BRANCH_MISSES) &&
464 runtime_branches_stats[cpu].n != 0) {
465 total = avg_stats(&runtime_branches_stats[cpu]);
468 ratio = avg * 100 / total;
470 fprintf(stderr, " # %5.2f %% of all branches ", ratio);
472 } else if (perf_evsel__match(evsel, HARDWARE, HW_CACHE_MISSES) &&
473 runtime_cacherefs_stats[cpu].n != 0) {
474 total = avg_stats(&runtime_cacherefs_stats[cpu]);
477 ratio = avg * 100 / total;
479 fprintf(stderr, " # %8.3f %% of all cache refs ", ratio);
481 } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES)) {
482 total = avg_stats(&runtime_cycles_stats[cpu]);
485 ratio = avg / total * 100.0;
487 fprintf(stderr, " # %5.2f%% of all cycles are idle ", ratio);
488 } else if (perf_evsel__match(evsel, HARDWARE, HW_CPU_CYCLES)) {
489 total = avg_stats(&runtime_nsecs_stats[cpu]);
492 ratio = 1.0 * avg / total;
494 fprintf(stderr, " # %8.3f GHz ", ratio);
495 } else if (runtime_nsecs_stats[cpu].n != 0) {
496 total = avg_stats(&runtime_nsecs_stats[cpu]);
499 ratio = 1000.0 * avg / total;
501 fprintf(stderr, " # %8.3f M/sec ", ratio);
506 * Print out the results of a single counter:
507 * aggregated counts in system-wide mode
509 static void print_counter_aggr(struct perf_evsel *counter)
511 struct perf_stat *ps = counter->priv;
512 double avg = avg_stats(&ps->res_stats[0]);
513 int scaled = counter->counts->scaled;
516 fprintf(stderr, "%*s%s%*s",
520 csv_output ? 0 : -24,
521 event_name(counter));
524 fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
530 if (nsec_counter(counter))
531 nsec_printout(-1, counter, avg);
533 abs_printout(-1, counter, avg);
540 print_noise(counter, avg);
543 double avg_enabled, avg_running;
545 avg_enabled = avg_stats(&ps->res_stats[1]);
546 avg_running = avg_stats(&ps->res_stats[2]);
548 fprintf(stderr, " (scaled from %.2f%%)",
549 100 * avg_running / avg_enabled);
551 fprintf(stderr, "\n");
555 * Print out the results of a single counter:
556 * does not use aggregated count in system-wide
558 static void print_counter(struct perf_evsel *counter)
563 for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
564 val = counter->counts->cpu[cpu].val;
565 ena = counter->counts->cpu[cpu].ena;
566 run = counter->counts->cpu[cpu].run;
567 if (run == 0 || ena == 0) {
568 fprintf(stderr, "CPU%*d%s%*s%s%*s",
570 evsel_list->cpus->map[cpu], csv_sep,
572 "<not counted>", csv_sep,
573 csv_output ? 0 : -24,
574 event_name(counter));
577 fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
583 if (nsec_counter(counter))
584 nsec_printout(cpu, counter, val);
586 abs_printout(cpu, counter, val);
589 print_noise(counter, 1.0);
592 fprintf(stderr, " (scaled from %.2f%%)",
600 static void print_stat(int argc, const char **argv)
602 struct perf_evsel *counter;
608 fprintf(stderr, "\n");
609 fprintf(stderr, " Performance counter stats for ");
610 if(target_pid == -1 && target_tid == -1) {
611 fprintf(stderr, "\'%s", argv[0]);
612 for (i = 1; i < argc; i++)
613 fprintf(stderr, " %s", argv[i]);
614 } else if (target_pid != -1)
615 fprintf(stderr, "process id \'%d", target_pid);
617 fprintf(stderr, "thread id \'%d", target_tid);
619 fprintf(stderr, "\'");
621 fprintf(stderr, " (%d runs)", run_count);
622 fprintf(stderr, ":\n\n");
626 list_for_each_entry(counter, &evsel_list->entries, node)
627 print_counter(counter);
629 list_for_each_entry(counter, &evsel_list->entries, node)
630 print_counter_aggr(counter);
634 fprintf(stderr, "\n");
635 fprintf(stderr, " %18.9f seconds time elapsed",
636 avg_stats(&walltime_nsecs_stats)/1e9);
638 fprintf(stderr, " ( +-%5.2f%% )",
639 100*stddev_stats(&walltime_nsecs_stats) /
640 avg_stats(&walltime_nsecs_stats));
642 fprintf(stderr, "\n\n");
646 static volatile int signr = -1;
648 static void skip_signal(int signo)
656 static void sig_atexit(void)
659 kill(child_pid, SIGTERM);
664 signal(signr, SIG_DFL);
665 kill(getpid(), signr);
668 static const char * const stat_usage[] = {
669 "perf stat [<options>] [<command>]",
673 static int stat__set_big_num(const struct option *opt __used,
674 const char *s __used, int unset)
676 big_num_opt = unset ? 0 : 1;
680 static const struct option options[] = {
681 OPT_CALLBACK('e', "event", &evsel_list, "event",
682 "event selector. use 'perf list' to list available events",
684 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
685 "event filter", parse_filter),
686 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
687 "child tasks do not inherit counters"),
688 OPT_INTEGER('p', "pid", &target_pid,
689 "stat events on existing process id"),
690 OPT_INTEGER('t', "tid", &target_tid,
691 "stat events on existing thread id"),
692 OPT_BOOLEAN('a', "all-cpus", &system_wide,
693 "system-wide collection from all CPUs"),
694 OPT_BOOLEAN('c', "scale", &scale,
695 "scale/normalize counters"),
696 OPT_INCR('v', "verbose", &verbose,
697 "be more verbose (show counter open errors, etc)"),
698 OPT_INTEGER('r', "repeat", &run_count,
699 "repeat command and print average + stddev (max: 100)"),
700 OPT_BOOLEAN('n', "null", &null_run,
701 "null run - dont start any counters"),
702 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
703 "print large numbers with thousands\' separators",
705 OPT_STRING('C', "cpu", &cpu_list, "cpu",
706 "list of cpus to monitor in system-wide"),
707 OPT_BOOLEAN('A', "no-aggr", &no_aggr,
708 "disable CPU count aggregation"),
709 OPT_STRING('x', "field-separator", &csv_sep, "separator",
710 "print counts with custom separator"),
711 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
712 "monitor event in cgroup name only",
717 int cmd_stat(int argc, const char **argv, const char *prefix __used)
719 struct perf_evsel *pos;
720 int status = -ENOMEM;
722 setlocale(LC_ALL, "");
724 evsel_list = perf_evlist__new(NULL, NULL);
725 if (evsel_list == NULL)
728 argc = parse_options(argc, argv, options, stat_usage,
729 PARSE_OPT_STOP_AT_NON_OPTION);
734 csv_sep = DEFAULT_SEPARATOR;
737 * let the spreadsheet do the pretty-printing
740 /* User explicitely passed -B? */
741 if (big_num_opt == 1) {
742 fprintf(stderr, "-B option not supported with -x\n");
743 usage_with_options(stat_usage, options);
744 } else /* Nope, so disable big number formatting */
746 } else if (big_num_opt == 0) /* User passed --no-big-num */
749 if (!argc && target_pid == -1 && target_tid == -1)
750 usage_with_options(stat_usage, options);
752 usage_with_options(stat_usage, options);
754 /* no_aggr, cgroup are for system-wide only */
755 if ((no_aggr || nr_cgroups) && !system_wide) {
756 fprintf(stderr, "both cgroup and no-aggregation "
757 "modes only available in system-wide mode\n");
759 usage_with_options(stat_usage, options);
762 /* Set attrs and nr_counters if no event is selected and !null_run */
763 if (!null_run && !evsel_list->nr_entries) {
766 for (c = 0; c < ARRAY_SIZE(default_attrs); ++c) {
767 pos = perf_evsel__new(&default_attrs[c], c);
770 perf_evlist__add(evsel_list, pos);
774 if (target_pid != -1)
775 target_tid = target_pid;
777 evsel_list->threads = thread_map__new(target_pid, target_tid);
778 if (evsel_list->threads == NULL) {
779 pr_err("Problems finding threads of monitor\n");
780 usage_with_options(stat_usage, options);
784 evsel_list->cpus = cpu_map__new(cpu_list);
786 evsel_list->cpus = cpu_map__dummy_new();
788 if (evsel_list->cpus == NULL) {
789 perror("failed to parse CPUs map");
790 usage_with_options(stat_usage, options);
794 list_for_each_entry(pos, &evsel_list->entries, node) {
795 if (perf_evsel__alloc_stat_priv(pos) < 0 ||
796 perf_evsel__alloc_counts(pos, evsel_list->cpus->nr) < 0 ||
797 perf_evsel__alloc_fd(pos, evsel_list->cpus->nr, evsel_list->threads->nr) < 0)
802 * We dont want to block the signals - that would cause
803 * child tasks to inherit that and Ctrl-C would not work.
804 * What we want is for Ctrl-C to work in the exec()-ed
805 * task, but being ignored by perf stat itself:
808 signal(SIGINT, skip_signal);
809 signal(SIGALRM, skip_signal);
810 signal(SIGABRT, skip_signal);
813 for (run_idx = 0; run_idx < run_count; run_idx++) {
814 if (run_count != 1 && verbose)
815 fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
816 status = run_perf_stat(argc, argv);
820 print_stat(argc, argv);
822 list_for_each_entry(pos, &evsel_list->entries, node)
823 perf_evsel__free_stat_priv(pos);
824 perf_evlist__delete_maps(evsel_list);
826 perf_evlist__delete(evsel_list);