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/evsel.h"
47 #include "util/debug.h"
48 #include "util/header.h"
49 #include "util/cpumap.h"
50 #include "util/thread.h"
52 #include <sys/prctl.h>
56 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
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_INSTRUCTIONS
},
69 { .type
= PERF_TYPE_HARDWARE
, .config
= PERF_COUNT_HW_BRANCH_INSTRUCTIONS
},
70 { .type
= PERF_TYPE_HARDWARE
, .config
= PERF_COUNT_HW_BRANCH_MISSES
},
71 { .type
= PERF_TYPE_HARDWARE
, .config
= PERF_COUNT_HW_CACHE_REFERENCES
},
72 { .type
= PERF_TYPE_HARDWARE
, .config
= PERF_COUNT_HW_CACHE_MISSES
},
76 static bool system_wide
= false;
77 static int nr_cpus
= 0;
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
*all_tids
= NULL
;
87 static int thread_num
= 0;
88 static pid_t child_pid
= -1;
89 static bool null_run
= false;
90 static bool big_num
= true;
91 static int big_num_opt
= -1;
92 static const char *cpu_list
;
93 static const char *csv_sep
= NULL
;
94 static bool csv_output
= false;
96 static volatile int done
= 0;
104 struct stats res_stats
[3];
107 static int perf_evsel__alloc_stat_priv(struct perf_evsel
*evsel
)
109 evsel
->priv
= zalloc(sizeof(struct perf_stat
));
110 return evsel
->priv
== NULL
? -ENOMEM
: 0;
113 static void perf_evsel__free_stat_priv(struct perf_evsel
*evsel
)
119 static void update_stats(struct stats
*stats
, u64 val
)
124 delta
= val
- stats
->mean
;
125 stats
->mean
+= delta
/ stats
->n
;
126 stats
->M2
+= delta
*(val
- stats
->mean
);
129 static double avg_stats(struct stats
*stats
)
135 * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
137 * (\Sum n_i^2) - ((\Sum n_i)^2)/n
138 * s^2 = -------------------------------
141 * http://en.wikipedia.org/wiki/Stddev
143 * The std dev of the mean is related to the std dev by:
150 static double stddev_stats(struct stats
*stats
)
152 double variance
= stats
->M2
/ (stats
->n
- 1);
153 double variance_mean
= variance
/ stats
->n
;
155 return sqrt(variance_mean
);
158 struct stats runtime_nsecs_stats
[MAX_NR_CPUS
];
159 struct stats runtime_cycles_stats
[MAX_NR_CPUS
];
160 struct stats runtime_branches_stats
[MAX_NR_CPUS
];
161 struct stats walltime_nsecs_stats
;
163 #define ERR_PERF_OPEN \
164 "counter %d, sys_perf_event_open() syscall returned with %d (%s). /bin/dmesg may provide additional information."
166 static int create_perf_stat_counter(struct perf_evsel
*evsel
, bool *perm_err
)
168 struct perf_event_attr
*attr
= &evsel
->attr
;
173 attr
->read_format
= PERF_FORMAT_TOTAL_TIME_ENABLED
|
174 PERF_FORMAT_TOTAL_TIME_RUNNING
;
179 for (cpu
= 0; cpu
< nr_cpus
; cpu
++) {
180 FD(evsel
, cpu
, 0) = sys_perf_event_open(attr
,
181 -1, cpumap
[cpu
], -1, 0);
182 if (FD(evsel
, cpu
, 0) < 0) {
183 if (errno
== EPERM
|| errno
== EACCES
)
185 error(ERR_PERF_OPEN
, evsel
->idx
,
186 FD(evsel
, cpu
, 0), strerror(errno
));
192 attr
->inherit
= !no_inherit
;
193 if (target_pid
== -1 && target_tid
== -1) {
195 attr
->enable_on_exec
= 1;
197 for (thread
= 0; thread
< thread_num
; thread
++) {
198 FD(evsel
, 0, thread
) = sys_perf_event_open(attr
,
199 all_tids
[thread
], -1, -1, 0);
200 if (FD(evsel
, 0, thread
) < 0) {
201 if (errno
== EPERM
|| errno
== EACCES
)
203 error(ERR_PERF_OPEN
, evsel
->idx
,
204 FD(evsel
, 0, thread
),
216 * Does the counter have nsecs as a unit?
218 static inline int nsec_counter(struct perf_evsel
*evsel
)
220 if (perf_evsel__match(evsel
, SOFTWARE
, SW_CPU_CLOCK
) ||
221 perf_evsel__match(evsel
, SOFTWARE
, SW_TASK_CLOCK
))
228 * Read out the results of a single counter:
229 * aggregate counts across CPUs in system-wide mode
231 static int read_counter_aggr(struct perf_evsel
*counter
)
233 struct perf_stat
*ps
= counter
->priv
;
234 u64
*count
= counter
->counts
->aggr
.values
;
237 if (__perf_evsel__read(counter
, nr_cpus
, thread_num
, scale
) < 0)
240 for (i
= 0; i
< 3; i
++)
241 update_stats(&ps
->res_stats
[i
], count
[i
]);
244 fprintf(stderr
, "%s: %Ld %Ld %Ld\n", event_name(counter
),
245 count
[0], count
[1], count
[2]);
249 * Save the full runtime - to allow normalization during printout:
251 if (perf_evsel__match(counter
, SOFTWARE
, SW_TASK_CLOCK
))
252 update_stats(&runtime_nsecs_stats
[0], count
[0]);
253 if (perf_evsel__match(counter
, HARDWARE
, HW_CPU_CYCLES
))
254 update_stats(&runtime_cycles_stats
[0], count
[0]);
255 if (perf_evsel__match(counter
, HARDWARE
, HW_BRANCH_INSTRUCTIONS
))
256 update_stats(&runtime_branches_stats
[0], count
[0]);
262 * Read out the results of a single counter:
263 * do not aggregate counts across CPUs in system-wide mode
265 static int read_counter(struct perf_evsel
*counter
)
270 for (cpu
= 0; cpu
< nr_cpus
; cpu
++) {
271 if (__perf_evsel__read_on_cpu(counter
, cpu
, 0, scale
) < 0)
274 count
= counter
->counts
->cpu
[cpu
].values
;
276 if (perf_evsel__match(counter
, SOFTWARE
, SW_TASK_CLOCK
))
277 update_stats(&runtime_nsecs_stats
[cpu
], count
[0]);
278 if (perf_evsel__match(counter
, HARDWARE
, HW_CPU_CYCLES
))
279 update_stats(&runtime_cycles_stats
[cpu
], count
[0]);
280 if (perf_evsel__match(counter
, HARDWARE
, HW_BRANCH_INSTRUCTIONS
))
281 update_stats(&runtime_branches_stats
[cpu
], count
[0]);
287 static int run_perf_stat(int argc __used
, const char **argv
)
289 unsigned long long t0
, t1
;
290 struct perf_evsel
*counter
;
293 int child_ready_pipe
[2], go_pipe
[2];
294 bool perm_err
= false;
295 const bool forks
= (argc
> 0);
301 if (forks
&& (pipe(child_ready_pipe
) < 0 || pipe(go_pipe
) < 0)) {
302 perror("failed to create pipes");
307 if ((child_pid
= fork()) < 0)
308 perror("failed to fork");
311 close(child_ready_pipe
[0]);
313 fcntl(go_pipe
[0], F_SETFD
, FD_CLOEXEC
);
316 * Do a dummy execvp to get the PLT entry resolved,
317 * so we avoid the resolver overhead on the real
320 execvp("", (char **)argv
);
323 * Tell the parent we're ready to go
325 close(child_ready_pipe
[1]);
328 * Wait until the parent tells us to go.
330 if (read(go_pipe
[0], &buf
, 1) == -1)
331 perror("unable to read pipe");
333 execvp(argv
[0], (char **)argv
);
339 if (target_tid
== -1 && target_pid
== -1 && !system_wide
)
340 all_tids
[0] = child_pid
;
343 * Wait for the child to be ready to exec.
345 close(child_ready_pipe
[1]);
347 if (read(child_ready_pipe
[0], &buf
, 1) == -1)
348 perror("unable to read pipe");
349 close(child_ready_pipe
[0]);
352 list_for_each_entry(counter
, &evsel_list
, node
)
353 ncreated
+= create_perf_stat_counter(counter
, &perm_err
);
355 if (ncreated
< nr_counters
) {
357 error("You may not have permission to collect %sstats.\n"
358 "\t Consider tweaking"
359 " /proc/sys/kernel/perf_event_paranoid or running as root.",
360 system_wide
? "system-wide " : "");
361 die("Not all events could be opened.\n");
363 kill(child_pid
, SIGTERM
);
368 * Enable counters and exec the command:
376 while(!done
) sleep(1);
381 update_stats(&walltime_nsecs_stats
, t1
- t0
);
384 list_for_each_entry(counter
, &evsel_list
, node
) {
385 read_counter(counter
);
386 perf_evsel__close_fd(counter
, nr_cpus
, 1);
389 list_for_each_entry(counter
, &evsel_list
, node
) {
390 read_counter_aggr(counter
);
391 perf_evsel__close_fd(counter
, nr_cpus
, thread_num
);
395 return WEXITSTATUS(status
);
398 static void print_noise(struct perf_evsel
*evsel
, double avg
)
400 struct perf_stat
*ps
;
406 fprintf(stderr
, " ( +- %7.3f%% )",
407 100 * stddev_stats(&ps
->res_stats
[0]) / avg
);
410 static void nsec_printout(int cpu
, struct perf_evsel
*evsel
, double avg
)
412 double msecs
= avg
/ 1e6
;
413 char cpustr
[16] = { '\0', };
414 const char *fmt
= csv_output
? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
417 sprintf(cpustr
, "CPU%*d%s",
419 cpumap
[cpu
], csv_sep
);
421 fprintf(stderr
, fmt
, cpustr
, msecs
, csv_sep
, event_name(evsel
));
426 if (perf_evsel__match(evsel
, SOFTWARE
, SW_TASK_CLOCK
))
427 fprintf(stderr
, " # %10.3f CPUs ",
428 avg
/ avg_stats(&walltime_nsecs_stats
));
431 static void abs_printout(int cpu
, struct perf_evsel
*evsel
, double avg
)
433 double total
, ratio
= 0.0;
434 char cpustr
[16] = { '\0', };
440 fmt
= "%s%'18.0f%s%-24s";
442 fmt
= "%s%18.0f%s%-24s";
445 sprintf(cpustr
, "CPU%*d%s",
447 cpumap
[cpu
], csv_sep
);
451 fprintf(stderr
, fmt
, cpustr
, avg
, csv_sep
, event_name(evsel
));
456 if (perf_evsel__match(evsel
, HARDWARE
, HW_INSTRUCTIONS
)) {
457 total
= avg_stats(&runtime_cycles_stats
[cpu
]);
462 fprintf(stderr
, " # %10.3f IPC ", 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
, " # %10.3f %% ", ratio
);
472 } else if (runtime_nsecs_stats
[cpu
].n
!= 0) {
473 total
= avg_stats(&runtime_nsecs_stats
[cpu
]);
476 ratio
= 1000.0 * avg
/ total
;
478 fprintf(stderr
, " # %10.3f M/sec", ratio
);
483 * Print out the results of a single counter:
484 * aggregated counts in system-wide mode
486 static void print_counter_aggr(struct perf_evsel
*counter
)
488 struct perf_stat
*ps
= counter
->priv
;
489 double avg
= avg_stats(&ps
->res_stats
[0]);
490 int scaled
= counter
->counts
->scaled
;
493 fprintf(stderr
, "%*s%s%-24s\n",
495 "<not counted>", csv_sep
, event_name(counter
));
499 if (nsec_counter(counter
))
500 nsec_printout(-1, counter
, avg
);
502 abs_printout(-1, counter
, avg
);
509 print_noise(counter
, avg
);
512 double avg_enabled
, avg_running
;
514 avg_enabled
= avg_stats(&ps
->res_stats
[1]);
515 avg_running
= avg_stats(&ps
->res_stats
[2]);
517 fprintf(stderr
, " (scaled from %.2f%%)",
518 100 * avg_running
/ avg_enabled
);
521 fprintf(stderr
, "\n");
525 * Print out the results of a single counter:
526 * does not use aggregated count in system-wide
528 static void print_counter(struct perf_evsel
*counter
)
533 for (cpu
= 0; cpu
< nr_cpus
; cpu
++) {
534 val
= counter
->counts
->cpu
[cpu
].val
;
535 ena
= counter
->counts
->cpu
[cpu
].ena
;
536 run
= counter
->counts
->cpu
[cpu
].run
;
537 if (run
== 0 || ena
== 0) {
538 fprintf(stderr
, "CPU%*d%s%*s%s%-24s",
540 cpumap
[cpu
], csv_sep
,
542 "<not counted>", csv_sep
,
543 event_name(counter
));
545 fprintf(stderr
, "\n");
549 if (nsec_counter(counter
))
550 nsec_printout(cpu
, counter
, val
);
552 abs_printout(cpu
, counter
, val
);
555 print_noise(counter
, 1.0);
558 fprintf(stderr
, " (scaled from %.2f%%)",
562 fprintf(stderr
, "\n");
566 static void print_stat(int argc
, const char **argv
)
568 struct perf_evsel
*counter
;
574 fprintf(stderr
, "\n");
575 fprintf(stderr
, " Performance counter stats for ");
576 if(target_pid
== -1 && target_tid
== -1) {
577 fprintf(stderr
, "\'%s", argv
[0]);
578 for (i
= 1; i
< argc
; i
++)
579 fprintf(stderr
, " %s", argv
[i
]);
580 } else if (target_pid
!= -1)
581 fprintf(stderr
, "process id \'%d", target_pid
);
583 fprintf(stderr
, "thread id \'%d", target_tid
);
585 fprintf(stderr
, "\'");
587 fprintf(stderr
, " (%d runs)", run_count
);
588 fprintf(stderr
, ":\n\n");
592 list_for_each_entry(counter
, &evsel_list
, node
)
593 print_counter(counter
);
595 list_for_each_entry(counter
, &evsel_list
, node
)
596 print_counter_aggr(counter
);
600 fprintf(stderr
, "\n");
601 fprintf(stderr
, " %18.9f seconds time elapsed",
602 avg_stats(&walltime_nsecs_stats
)/1e9
);
604 fprintf(stderr
, " ( +- %7.3f%% )",
605 100*stddev_stats(&walltime_nsecs_stats
) /
606 avg_stats(&walltime_nsecs_stats
));
608 fprintf(stderr
, "\n\n");
612 static volatile int signr
= -1;
614 static void skip_signal(int signo
)
622 static void sig_atexit(void)
625 kill(child_pid
, SIGTERM
);
630 signal(signr
, SIG_DFL
);
631 kill(getpid(), signr
);
634 static const char * const stat_usage
[] = {
635 "perf stat [<options>] [<command>]",
639 static int stat__set_big_num(const struct option
*opt __used
,
640 const char *s __used
, int unset
)
642 big_num_opt
= unset
? 0 : 1;
646 static const struct option options
[] = {
647 OPT_CALLBACK('e', "event", NULL
, "event",
648 "event selector. use 'perf list' to list available events",
650 OPT_BOOLEAN('i', "no-inherit", &no_inherit
,
651 "child tasks do not inherit counters"),
652 OPT_INTEGER('p', "pid", &target_pid
,
653 "stat events on existing process id"),
654 OPT_INTEGER('t', "tid", &target_tid
,
655 "stat events on existing thread id"),
656 OPT_BOOLEAN('a', "all-cpus", &system_wide
,
657 "system-wide collection from all CPUs"),
658 OPT_BOOLEAN('c', "scale", &scale
,
659 "scale/normalize counters"),
660 OPT_INCR('v', "verbose", &verbose
,
661 "be more verbose (show counter open errors, etc)"),
662 OPT_INTEGER('r', "repeat", &run_count
,
663 "repeat command and print average + stddev (max: 100)"),
664 OPT_BOOLEAN('n', "null", &null_run
,
665 "null run - dont start any counters"),
666 OPT_CALLBACK_NOOPT('B', "big-num", NULL
, NULL
,
667 "print large numbers with thousands\' separators",
669 OPT_STRING('C', "cpu", &cpu_list
, "cpu",
670 "list of cpus to monitor in system-wide"),
671 OPT_BOOLEAN('A', "no-aggr", &no_aggr
,
672 "disable CPU count aggregation"),
673 OPT_STRING('x', "field-separator", &csv_sep
, "separator",
674 "print counts with custom separator"),
678 int cmd_stat(int argc
, const char **argv
, const char *prefix __used
)
680 struct perf_evsel
*pos
;
681 int status
= -ENOMEM
;
683 setlocale(LC_ALL
, "");
685 argc
= parse_options(argc
, argv
, options
, stat_usage
,
686 PARSE_OPT_STOP_AT_NON_OPTION
);
691 csv_sep
= DEFAULT_SEPARATOR
;
694 * let the spreadsheet do the pretty-printing
697 /* User explicitely passed -B? */
698 if (big_num_opt
== 1) {
699 fprintf(stderr
, "-B option not supported with -x\n");
700 usage_with_options(stat_usage
, options
);
701 } else /* Nope, so disable big number formatting */
703 } else if (big_num_opt
== 0) /* User passed --no-big-num */
706 if (!argc
&& target_pid
== -1 && target_tid
== -1)
707 usage_with_options(stat_usage
, options
);
709 usage_with_options(stat_usage
, options
);
711 /* no_aggr is for system-wide only */
712 if (no_aggr
&& !system_wide
)
713 usage_with_options(stat_usage
, options
);
715 /* Set attrs and nr_counters if no event is selected and !null_run */
716 if (!null_run
&& !nr_counters
) {
719 nr_counters
= ARRAY_SIZE(default_attrs
);
721 for (c
= 0; c
< ARRAY_SIZE(default_attrs
); ++c
) {
722 pos
= perf_evsel__new(default_attrs
[c
].type
,
723 default_attrs
[c
].config
,
727 list_add(&pos
->node
, &evsel_list
);
732 nr_cpus
= read_cpu_map(cpu_list
);
737 usage_with_options(stat_usage
, options
);
739 if (target_pid
!= -1) {
740 target_tid
= target_pid
;
741 thread_num
= find_all_tid(target_pid
, &all_tids
);
742 if (thread_num
<= 0) {
743 fprintf(stderr
, "Can't find all threads of pid %d\n",
745 usage_with_options(stat_usage
, options
);
748 all_tids
=malloc(sizeof(pid_t
));
752 all_tids
[0] = target_tid
;
756 list_for_each_entry(pos
, &evsel_list
, node
) {
757 if (perf_evsel__alloc_stat_priv(pos
) < 0 ||
758 perf_evsel__alloc_counts(pos
, nr_cpus
) < 0 ||
759 perf_evsel__alloc_fd(pos
, nr_cpus
, thread_num
) < 0)
764 * We dont want to block the signals - that would cause
765 * child tasks to inherit that and Ctrl-C would not work.
766 * What we want is for Ctrl-C to work in the exec()-ed
767 * task, but being ignored by perf stat itself:
770 signal(SIGINT
, skip_signal
);
771 signal(SIGALRM
, skip_signal
);
772 signal(SIGABRT
, skip_signal
);
775 for (run_idx
= 0; run_idx
< run_count
; run_idx
++) {
776 if (run_count
!= 1 && verbose
)
777 fprintf(stderr
, "[ perf stat: executing run #%d ... ]\n", run_idx
+ 1);
778 status
= run_perf_stat(argc
, argv
);
782 print_stat(argc
, argv
);
784 list_for_each_entry(pos
, &evsel_list
, node
)
785 perf_evsel__free_stat_priv(pos
);