perf stat: Factor our shadow stats
[GitHub/mt8127/android_kernel_alcatel_ttab.git] / tools / perf / builtin-stat.c
CommitLineData
ddcacfa0 1/*
bf9e1876
IM
2 * builtin-stat.c
3 *
4 * Builtin stat command: Give a precise performance counters summary
5 * overview about any workload, CPU or specific PID.
6 *
7 * Sample output:
ddcacfa0 8
bf9e1876
IM
9 $ perf stat ~/hackbench 10
10 Time: 0.104
ddcacfa0 11
bf9e1876 12 Performance counter stats for '/home/mingo/hackbench':
ddcacfa0 13
bf9e1876
IM
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
ddcacfa0 22
bf9e1876 23 Wall-clock time elapsed: 123.786620 msecs
ddcacfa0 24
5242519b
IM
25 *
26 * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
27 *
28 * Improvements and fixes by:
29 *
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>
6e750a8f 35 * Jaswinder Singh Rajput <jaswinder@kernel.org>
5242519b
IM
36 *
37 * Released under the GPL v2. (and only v2, not any later version)
ddcacfa0
IM
38 */
39
1a482f38 40#include "perf.h"
16f762a2 41#include "builtin.h"
148be2c1 42#include "util/util.h"
5242519b
IM
43#include "util/parse-options.h"
44#include "util/parse-events.h"
8f28827a 45#include "util/event.h"
361c99a6 46#include "util/evlist.h"
69aad6f1 47#include "util/evsel.h"
8f28827a 48#include "util/debug.h"
60666c63 49#include "util/header.h"
a12b51c4 50#include "util/cpumap.h"
d6d901c2 51#include "util/thread.h"
fd78260b 52#include "util/thread_map.h"
ddcacfa0 53
ddcacfa0 54#include <sys/prctl.h>
42202dd5 55#include <math.h>
5af52b51 56#include <locale.h>
16c8a109 57
d7470b6a
SE
58#define DEFAULT_SEPARATOR " "
59
cdd6c482 60static struct perf_event_attr default_attrs[] = {
ddcacfa0 61
56aab464
IM
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 },
f4dbfa8f 66
56aab464
IM
67 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
68 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
56aab464
IM
69 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
70 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
dd86e72a
IM
71 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CACHE_REFERENCES },
72 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CACHE_MISSES },
f4dbfa8f 73
ddcacfa0 74};
5242519b 75
361c99a6
ACM
76struct perf_evlist *evsel_list;
77
c0555642 78static bool system_wide = false;
3d632595 79static int run_idx = 0;
ddcacfa0 80
3d632595 81static int run_count = 1;
2e6cdf99 82static bool no_inherit = false;
c0555642 83static bool scale = true;
f5b4a9c3 84static bool no_aggr = false;
933da83a 85static pid_t target_pid = -1;
d6d901c2 86static pid_t target_tid = -1;
933da83a 87static pid_t child_pid = -1;
c0555642 88static bool null_run = false;
201e0b06 89static bool big_num = true;
d7470b6a 90static int big_num_opt = -1;
c45c6ea2 91static const char *cpu_list;
d7470b6a
SE
92static const char *csv_sep = NULL;
93static bool csv_output = false;
5af52b51 94
60666c63
LW
95static volatile int done = 0;
96
506d4bc8
PZ
97struct stats
98{
8a02631a 99 double n, mean, M2;
506d4bc8 100};
42202dd5 101
69aad6f1
ACM
102struct perf_stat {
103 struct stats res_stats[3];
69aad6f1
ACM
104};
105
c52b12ed 106static int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel)
69aad6f1 107{
c52b12ed 108 evsel->priv = zalloc(sizeof(struct perf_stat));
69aad6f1
ACM
109 return evsel->priv == NULL ? -ENOMEM : 0;
110}
111
112static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
113{
114 free(evsel->priv);
115 evsel->priv = NULL;
116}
117
9e9772c4
PZ
118static void update_stats(struct stats *stats, u64 val)
119{
8a02631a 120 double delta;
9e9772c4 121
8a02631a
PZ
122 stats->n++;
123 delta = val - stats->mean;
124 stats->mean += delta / stats->n;
125 stats->M2 += delta*(val - stats->mean);
9e9772c4
PZ
126}
127
506d4bc8
PZ
128static double avg_stats(struct stats *stats)
129{
8a02631a 130 return stats->mean;
506d4bc8 131}
42202dd5 132
506d4bc8 133/*
63d40deb
PZ
134 * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
135 *
8a02631a
PZ
136 * (\Sum n_i^2) - ((\Sum n_i)^2)/n
137 * s^2 = -------------------------------
138 * n - 1
63d40deb
PZ
139 *
140 * http://en.wikipedia.org/wiki/Stddev
141 *
142 * The std dev of the mean is related to the std dev by:
143 *
144 * s
145 * s_mean = -------
146 * sqrt(n)
147 *
506d4bc8
PZ
148 */
149static double stddev_stats(struct stats *stats)
150{
8a02631a
PZ
151 double variance = stats->M2 / (stats->n - 1);
152 double variance_mean = variance / stats->n;
42202dd5 153
63d40deb 154 return sqrt(variance_mean);
506d4bc8 155}
42202dd5 156
f5b4a9c3
SE
157struct stats runtime_nsecs_stats[MAX_NR_CPUS];
158struct stats runtime_cycles_stats[MAX_NR_CPUS];
159struct stats runtime_branches_stats[MAX_NR_CPUS];
d58f4c82 160struct stats runtime_cacherefs_stats[MAX_NR_CPUS];
506d4bc8 161struct stats walltime_nsecs_stats;
be1ac0d8 162
48290609 163static int create_perf_stat_counter(struct perf_evsel *evsel)
ddcacfa0 164{
69aad6f1 165 struct perf_event_attr *attr = &evsel->attr;
16c8a109 166
ddcacfa0 167 if (scale)
a21ca2ca
IM
168 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
169 PERF_FORMAT_TOTAL_TIME_RUNNING;
ddcacfa0 170
5d2cd909
ACM
171 attr->inherit = !no_inherit;
172
48290609 173 if (system_wide)
5d2cd909 174 return perf_evsel__open_per_cpu(evsel, evsel_list->cpus, false);
48290609 175
48290609
ACM
176 if (target_pid == -1 && target_tid == -1) {
177 attr->disabled = 1;
178 attr->enable_on_exec = 1;
ddcacfa0 179 }
084ab9f8 180
5d2cd909 181 return perf_evsel__open_per_thread(evsel, evsel_list->threads, false);
ddcacfa0
IM
182}
183
c04f5e5d
IM
184/*
185 * Does the counter have nsecs as a unit?
186 */
daec78a0 187static inline int nsec_counter(struct perf_evsel *evsel)
c04f5e5d 188{
daec78a0
ACM
189 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
190 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
c04f5e5d
IM
191 return 1;
192
193 return 0;
194}
195
dcd9936a
IM
196/*
197 * Update various tracking values we maintain to print
198 * more semantic information such as miss/hit ratios,
199 * instruction rates, etc:
200 */
201static void update_shadow_stats(struct perf_evsel *counter, u64 *count)
202{
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_BRANCH_INSTRUCTIONS))
208 update_stats(&runtime_branches_stats[0], count[0]);
209 else if (perf_evsel__match(counter, HARDWARE, HW_CACHE_REFERENCES))
210 update_stats(&runtime_cacherefs_stats[0], count[0]);
211}
212
c04f5e5d 213/*
2996f5dd 214 * Read out the results of a single counter:
f5b4a9c3 215 * aggregate counts across CPUs in system-wide mode
c04f5e5d 216 */
c52b12ed 217static int read_counter_aggr(struct perf_evsel *counter)
c04f5e5d 218{
69aad6f1 219 struct perf_stat *ps = counter->priv;
c52b12ed
ACM
220 u64 *count = counter->counts->aggr.values;
221 int i;
2996f5dd 222
7e2ed097
ACM
223 if (__perf_evsel__read(counter, evsel_list->cpus->nr,
224 evsel_list->threads->nr, scale) < 0)
c52b12ed 225 return -1;
9e9772c4
PZ
226
227 for (i = 0; i < 3; i++)
69aad6f1 228 update_stats(&ps->res_stats[i], count[i]);
9e9772c4
PZ
229
230 if (verbose) {
9486aa38
ACM
231 fprintf(stderr, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
232 event_name(counter), count[0], count[1], count[2]);
9e9772c4
PZ
233 }
234
be1ac0d8
IM
235 /*
236 * Save the full runtime - to allow normalization during printout:
237 */
dcd9936a 238 update_shadow_stats(counter, count);
c52b12ed
ACM
239
240 return 0;
f5b4a9c3
SE
241}
242
243/*
244 * Read out the results of a single counter:
245 * do not aggregate counts across CPUs in system-wide mode
246 */
c52b12ed 247static int read_counter(struct perf_evsel *counter)
f5b4a9c3 248{
c52b12ed 249 u64 *count;
f5b4a9c3 250 int cpu;
f5b4a9c3 251
7e2ed097 252 for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
c52b12ed
ACM
253 if (__perf_evsel__read_on_cpu(counter, cpu, 0, scale) < 0)
254 return -1;
f5b4a9c3 255
c52b12ed 256 count = counter->counts->cpu[cpu].values;
f5b4a9c3 257
dcd9936a 258 update_shadow_stats(counter, count);
f5b4a9c3 259 }
c52b12ed
ACM
260
261 return 0;
2996f5dd
IM
262}
263
f37a291c 264static int run_perf_stat(int argc __used, const char **argv)
42202dd5
IM
265{
266 unsigned long long t0, t1;
69aad6f1 267 struct perf_evsel *counter;
42202dd5 268 int status = 0;
051ae7f7 269 int child_ready_pipe[2], go_pipe[2];
6be2850e 270 const bool forks = (argc > 0);
051ae7f7 271 char buf;
42202dd5 272
60666c63 273 if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
051ae7f7
PM
274 perror("failed to create pipes");
275 exit(1);
276 }
277
60666c63 278 if (forks) {
6be2850e 279 if ((child_pid = fork()) < 0)
60666c63
LW
280 perror("failed to fork");
281
6be2850e 282 if (!child_pid) {
60666c63
LW
283 close(child_ready_pipe[0]);
284 close(go_pipe[1]);
285 fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
286
287 /*
288 * Do a dummy execvp to get the PLT entry resolved,
289 * so we avoid the resolver overhead on the real
290 * execvp call.
291 */
292 execvp("", (char **)argv);
293
294 /*
295 * Tell the parent we're ready to go
296 */
297 close(child_ready_pipe[1]);
298
299 /*
300 * Wait until the parent tells us to go.
301 */
302 if (read(go_pipe[0], &buf, 1) == -1)
303 perror("unable to read pipe");
304
305 execvp(argv[0], (char **)argv);
306
307 perror(argv[0]);
308 exit(-1);
309 }
051ae7f7 310
d6d901c2 311 if (target_tid == -1 && target_pid == -1 && !system_wide)
7e2ed097 312 evsel_list->threads->map[0] = child_pid;
d6d901c2 313
051ae7f7 314 /*
60666c63 315 * Wait for the child to be ready to exec.
051ae7f7
PM
316 */
317 close(child_ready_pipe[1]);
60666c63
LW
318 close(go_pipe[0]);
319 if (read(child_ready_pipe[0], &buf, 1) == -1)
a92bef0f 320 perror("unable to read pipe");
60666c63 321 close(child_ready_pipe[0]);
051ae7f7
PM
322 }
323
361c99a6 324 list_for_each_entry(counter, &evsel_list->entries, node) {
48290609
ACM
325 if (create_perf_stat_counter(counter) < 0) {
326 if (errno == -EPERM || errno == -EACCES) {
327 error("You may not have permission to collect %sstats.\n"
328 "\t Consider tweaking"
329 " /proc/sys/kernel/perf_event_paranoid or running as root.",
330 system_wide ? "system-wide " : "");
5a3446bc
DA
331 } else if (errno == ENOENT) {
332 error("%s event is not supported. ", event_name(counter));
48290609
ACM
333 } else {
334 error("open_counter returned with %d (%s). "
335 "/bin/dmesg may provide additional information.\n",
336 errno, strerror(errno));
337 }
338 if (child_pid != -1)
339 kill(child_pid, SIGTERM);
340 die("Not all events could be opened.\n");
341 return -1;
342 }
084ab9f8 343 }
42202dd5 344
cfd748ae
FW
345 if (perf_evlist__set_filters(evsel_list)) {
346 error("failed to set filter with %d (%s)\n", errno,
347 strerror(errno));
348 return -1;
349 }
350
42202dd5
IM
351 /*
352 * Enable counters and exec the command:
353 */
354 t0 = rdclock();
42202dd5 355
60666c63
LW
356 if (forks) {
357 close(go_pipe[1]);
358 wait(&status);
359 } else {
6be2850e 360 while(!done) sleep(1);
60666c63 361 }
42202dd5 362
42202dd5
IM
363 t1 = rdclock();
364
9e9772c4 365 update_stats(&walltime_nsecs_stats, t1 - t0);
42202dd5 366
f5b4a9c3 367 if (no_aggr) {
361c99a6 368 list_for_each_entry(counter, &evsel_list->entries, node) {
f5b4a9c3 369 read_counter(counter);
7e2ed097 370 perf_evsel__close_fd(counter, evsel_list->cpus->nr, 1);
c52b12ed 371 }
f5b4a9c3 372 } else {
361c99a6 373 list_for_each_entry(counter, &evsel_list->entries, node) {
f5b4a9c3 374 read_counter_aggr(counter);
7e2ed097
ACM
375 perf_evsel__close_fd(counter, evsel_list->cpus->nr,
376 evsel_list->threads->nr);
c52b12ed 377 }
f5b4a9c3 378 }
c52b12ed 379
42202dd5
IM
380 return WEXITSTATUS(status);
381}
382
69aad6f1 383static void print_noise(struct perf_evsel *evsel, double avg)
42202dd5 384{
69aad6f1
ACM
385 struct perf_stat *ps;
386
849abde9
PZ
387 if (run_count == 1)
388 return;
389
69aad6f1 390 ps = evsel->priv;
849abde9 391 fprintf(stderr, " ( +- %7.3f%% )",
69aad6f1 392 100 * stddev_stats(&ps->res_stats[0]) / avg);
42202dd5
IM
393}
394
daec78a0 395static void nsec_printout(int cpu, struct perf_evsel *evsel, double avg)
44175b6f 396{
506d4bc8 397 double msecs = avg / 1e6;
d7470b6a
SE
398 char cpustr[16] = { '\0', };
399 const char *fmt = csv_output ? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
44175b6f 400
f5b4a9c3 401 if (no_aggr)
d7470b6a
SE
402 sprintf(cpustr, "CPU%*d%s",
403 csv_output ? 0 : -4,
7e2ed097 404 evsel_list->cpus->map[cpu], csv_sep);
d7470b6a 405
daec78a0 406 fprintf(stderr, fmt, cpustr, msecs, csv_sep, event_name(evsel));
d7470b6a 407
023695d9
SE
408 if (evsel->cgrp)
409 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
410
d7470b6a
SE
411 if (csv_output)
412 return;
44175b6f 413
daec78a0 414 if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
d58f4c82 415 fprintf(stderr, " # %10.3f CPUs",
506d4bc8 416 avg / avg_stats(&walltime_nsecs_stats));
44175b6f
IM
417}
418
daec78a0 419static void abs_printout(int cpu, struct perf_evsel *evsel, double avg)
44175b6f 420{
c7f7fea3 421 double total, ratio = 0.0;
f5b4a9c3 422 char cpustr[16] = { '\0', };
d7470b6a
SE
423 const char *fmt;
424
425 if (csv_output)
426 fmt = "%s%.0f%s%s";
427 else if (big_num)
428 fmt = "%s%'18.0f%s%-24s";
429 else
430 fmt = "%s%18.0f%s%-24s";
f5b4a9c3
SE
431
432 if (no_aggr)
d7470b6a
SE
433 sprintf(cpustr, "CPU%*d%s",
434 csv_output ? 0 : -4,
7e2ed097 435 evsel_list->cpus->map[cpu], csv_sep);
f5b4a9c3
SE
436 else
437 cpu = 0;
c7f7fea3 438
daec78a0 439 fprintf(stderr, fmt, cpustr, avg, csv_sep, event_name(evsel));
d7470b6a 440
023695d9
SE
441 if (evsel->cgrp)
442 fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
443
d7470b6a
SE
444 if (csv_output)
445 return;
44175b6f 446
daec78a0 447 if (perf_evsel__match(evsel, HARDWARE, HW_INSTRUCTIONS)) {
f5b4a9c3 448 total = avg_stats(&runtime_cycles_stats[cpu]);
c7f7fea3
IM
449
450 if (total)
451 ratio = avg / total;
452
11ba2b85 453 fprintf(stderr, " # ( %4.2f instructions per cycle )", ratio);
daec78a0 454 } else if (perf_evsel__match(evsel, HARDWARE, HW_BRANCH_MISSES) &&
f5b4a9c3
SE
455 runtime_branches_stats[cpu].n != 0) {
456 total = avg_stats(&runtime_branches_stats[cpu]);
11018201
AB
457
458 if (total)
459 ratio = avg * 100 / total;
460
11ba2b85 461 fprintf(stderr, " # %10.3f %%", ratio);
11018201 462
d58f4c82
IM
463 } else if (perf_evsel__match(evsel, HARDWARE, HW_CACHE_MISSES) &&
464 runtime_cacherefs_stats[cpu].n != 0) {
465 total = avg_stats(&runtime_cacherefs_stats[cpu]);
466
467 if (total)
468 ratio = avg * 100 / total;
469
470 fprintf(stderr, " # %10.3f %%", ratio);
471
f5b4a9c3
SE
472 } else if (runtime_nsecs_stats[cpu].n != 0) {
473 total = avg_stats(&runtime_nsecs_stats[cpu]);
c7f7fea3
IM
474
475 if (total)
476 ratio = 1000.0 * avg / total;
477
478 fprintf(stderr, " # %10.3f M/sec", ratio);
11ba2b85
IM
479 } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES)) {
480 total = avg_stats(&runtime_cycles_stats[cpu]);
481
482 if (total)
483 ratio = avg / total * 100.0;
484
485 fprintf(stderr, " # (%5.2f%% of all cycles )", ratio);
44175b6f 486 }
44175b6f
IM
487}
488
2996f5dd
IM
489/*
490 * Print out the results of a single counter:
f5b4a9c3 491 * aggregated counts in system-wide mode
2996f5dd 492 */
69aad6f1 493static void print_counter_aggr(struct perf_evsel *counter)
2996f5dd 494{
69aad6f1
ACM
495 struct perf_stat *ps = counter->priv;
496 double avg = avg_stats(&ps->res_stats[0]);
c52b12ed 497 int scaled = counter->counts->scaled;
2996f5dd 498
2996f5dd 499 if (scaled == -1) {
023695d9 500 fprintf(stderr, "%*s%s%*s",
d7470b6a 501 csv_output ? 0 : 18,
023695d9
SE
502 "<not counted>",
503 csv_sep,
504 csv_output ? 0 : -24,
505 event_name(counter));
506
507 if (counter->cgrp)
508 fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
509
510 fputc('\n', stderr);
2996f5dd
IM
511 return;
512 }
c04f5e5d 513
44175b6f 514 if (nsec_counter(counter))
f5b4a9c3 515 nsec_printout(-1, counter, avg);
44175b6f 516 else
f5b4a9c3 517 abs_printout(-1, counter, avg);
849abde9 518
d7470b6a
SE
519 if (csv_output) {
520 fputc('\n', stderr);
521 return;
522 }
523
849abde9 524 print_noise(counter, avg);
506d4bc8
PZ
525
526 if (scaled) {
527 double avg_enabled, avg_running;
528
69aad6f1
ACM
529 avg_enabled = avg_stats(&ps->res_stats[1]);
530 avg_running = avg_stats(&ps->res_stats[2]);
d7c29318 531
210ad39f 532 fprintf(stderr, " (scaled from %.2f%%)",
506d4bc8
PZ
533 100 * avg_running / avg_enabled);
534 }
c04f5e5d
IM
535 fprintf(stderr, "\n");
536}
537
f5b4a9c3
SE
538/*
539 * Print out the results of a single counter:
540 * does not use aggregated count in system-wide
541 */
69aad6f1 542static void print_counter(struct perf_evsel *counter)
f5b4a9c3
SE
543{
544 u64 ena, run, val;
545 int cpu;
546
7e2ed097 547 for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
c52b12ed
ACM
548 val = counter->counts->cpu[cpu].val;
549 ena = counter->counts->cpu[cpu].ena;
550 run = counter->counts->cpu[cpu].run;
f5b4a9c3 551 if (run == 0 || ena == 0) {
023695d9 552 fprintf(stderr, "CPU%*d%s%*s%s%*s",
d7470b6a 553 csv_output ? 0 : -4,
7e2ed097 554 evsel_list->cpus->map[cpu], csv_sep,
d7470b6a
SE
555 csv_output ? 0 : 18,
556 "<not counted>", csv_sep,
023695d9 557 csv_output ? 0 : -24,
d7470b6a 558 event_name(counter));
f5b4a9c3 559
023695d9
SE
560 if (counter->cgrp)
561 fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
562
563 fputc('\n', stderr);
f5b4a9c3
SE
564 continue;
565 }
566
567 if (nsec_counter(counter))
568 nsec_printout(cpu, counter, val);
569 else
570 abs_printout(cpu, counter, val);
571
d7470b6a
SE
572 if (!csv_output) {
573 print_noise(counter, 1.0);
f5b4a9c3 574
d7470b6a
SE
575 if (run != ena) {
576 fprintf(stderr, " (scaled from %.2f%%)",
f5b4a9c3 577 100.0 * run / ena);
d7470b6a 578 }
f5b4a9c3 579 }
023695d9 580 fputc('\n', stderr);
f5b4a9c3
SE
581 }
582}
583
42202dd5
IM
584static void print_stat(int argc, const char **argv)
585{
69aad6f1
ACM
586 struct perf_evsel *counter;
587 int i;
42202dd5 588
ddcacfa0
IM
589 fflush(stdout);
590
d7470b6a
SE
591 if (!csv_output) {
592 fprintf(stderr, "\n");
593 fprintf(stderr, " Performance counter stats for ");
594 if(target_pid == -1 && target_tid == -1) {
595 fprintf(stderr, "\'%s", argv[0]);
596 for (i = 1; i < argc; i++)
597 fprintf(stderr, " %s", argv[i]);
598 } else if (target_pid != -1)
599 fprintf(stderr, "process id \'%d", target_pid);
600 else
601 fprintf(stderr, "thread id \'%d", target_tid);
44db76c8 602
d7470b6a
SE
603 fprintf(stderr, "\'");
604 if (run_count > 1)
605 fprintf(stderr, " (%d runs)", run_count);
606 fprintf(stderr, ":\n\n");
607 }
2996f5dd 608
f5b4a9c3 609 if (no_aggr) {
361c99a6 610 list_for_each_entry(counter, &evsel_list->entries, node)
f5b4a9c3
SE
611 print_counter(counter);
612 } else {
361c99a6 613 list_for_each_entry(counter, &evsel_list->entries, node)
f5b4a9c3
SE
614 print_counter_aggr(counter);
615 }
ddcacfa0 616
d7470b6a
SE
617 if (!csv_output) {
618 fprintf(stderr, "\n");
619 fprintf(stderr, " %18.9f seconds time elapsed",
620 avg_stats(&walltime_nsecs_stats)/1e9);
621 if (run_count > 1) {
622 fprintf(stderr, " ( +- %7.3f%% )",
506d4bc8
PZ
623 100*stddev_stats(&walltime_nsecs_stats) /
624 avg_stats(&walltime_nsecs_stats));
d7470b6a
SE
625 }
626 fprintf(stderr, "\n\n");
566747e6 627 }
ddcacfa0
IM
628}
629
f7b7c26e
PZ
630static volatile int signr = -1;
631
5242519b 632static void skip_signal(int signo)
ddcacfa0 633{
6be2850e 634 if(child_pid == -1)
60666c63
LW
635 done = 1;
636
f7b7c26e
PZ
637 signr = signo;
638}
639
640static void sig_atexit(void)
641{
933da83a
CW
642 if (child_pid != -1)
643 kill(child_pid, SIGTERM);
644
f7b7c26e
PZ
645 if (signr == -1)
646 return;
647
648 signal(signr, SIG_DFL);
649 kill(getpid(), signr);
5242519b
IM
650}
651
652static const char * const stat_usage[] = {
60666c63 653 "perf stat [<options>] [<command>]",
5242519b
IM
654 NULL
655};
656
d7470b6a
SE
657static int stat__set_big_num(const struct option *opt __used,
658 const char *s __used, int unset)
659{
660 big_num_opt = unset ? 0 : 1;
661 return 0;
662}
663
5242519b 664static const struct option options[] = {
361c99a6 665 OPT_CALLBACK('e', "event", &evsel_list, "event",
86847b62
TG
666 "event selector. use 'perf list' to list available events",
667 parse_events),
cfd748ae
FW
668 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
669 "event filter", parse_filter),
2e6cdf99
SE
670 OPT_BOOLEAN('i', "no-inherit", &no_inherit,
671 "child tasks do not inherit counters"),
5242519b 672 OPT_INTEGER('p', "pid", &target_pid,
d6d901c2
ZY
673 "stat events on existing process id"),
674 OPT_INTEGER('t', "tid", &target_tid,
675 "stat events on existing thread id"),
5242519b 676 OPT_BOOLEAN('a', "all-cpus", &system_wide,
3d632595 677 "system-wide collection from all CPUs"),
b26bc5a7 678 OPT_BOOLEAN('c', "scale", &scale,
3d632595 679 "scale/normalize counters"),
c0555642 680 OPT_INCR('v', "verbose", &verbose,
743ee1f8 681 "be more verbose (show counter open errors, etc)"),
42202dd5
IM
682 OPT_INTEGER('r', "repeat", &run_count,
683 "repeat command and print average + stddev (max: 100)"),
0cfb7a13
IM
684 OPT_BOOLEAN('n', "null", &null_run,
685 "null run - dont start any counters"),
d7470b6a
SE
686 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
687 "print large numbers with thousands\' separators",
688 stat__set_big_num),
c45c6ea2
SE
689 OPT_STRING('C', "cpu", &cpu_list, "cpu",
690 "list of cpus to monitor in system-wide"),
f5b4a9c3
SE
691 OPT_BOOLEAN('A', "no-aggr", &no_aggr,
692 "disable CPU count aggregation"),
d7470b6a
SE
693 OPT_STRING('x', "field-separator", &csv_sep, "separator",
694 "print counts with custom separator"),
023695d9
SE
695 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
696 "monitor event in cgroup name only",
697 parse_cgroups),
5242519b
IM
698 OPT_END()
699};
700
f37a291c 701int cmd_stat(int argc, const char **argv, const char *prefix __used)
5242519b 702{
69aad6f1
ACM
703 struct perf_evsel *pos;
704 int status = -ENOMEM;
42202dd5 705
5af52b51
SE
706 setlocale(LC_ALL, "");
707
7e2ed097 708 evsel_list = perf_evlist__new(NULL, NULL);
361c99a6
ACM
709 if (evsel_list == NULL)
710 return -ENOMEM;
711
a0541234
AB
712 argc = parse_options(argc, argv, options, stat_usage,
713 PARSE_OPT_STOP_AT_NON_OPTION);
d7470b6a
SE
714
715 if (csv_sep)
716 csv_output = true;
717 else
718 csv_sep = DEFAULT_SEPARATOR;
719
720 /*
721 * let the spreadsheet do the pretty-printing
722 */
723 if (csv_output) {
724 /* User explicitely passed -B? */
725 if (big_num_opt == 1) {
726 fprintf(stderr, "-B option not supported with -x\n");
727 usage_with_options(stat_usage, options);
728 } else /* Nope, so disable big number formatting */
729 big_num = false;
730 } else if (big_num_opt == 0) /* User passed --no-big-num */
731 big_num = false;
732
d6d901c2 733 if (!argc && target_pid == -1 && target_tid == -1)
5242519b 734 usage_with_options(stat_usage, options);
9e9772c4 735 if (run_count <= 0)
42202dd5 736 usage_with_options(stat_usage, options);
ddcacfa0 737
023695d9
SE
738 /* no_aggr, cgroup are for system-wide only */
739 if ((no_aggr || nr_cgroups) && !system_wide) {
740 fprintf(stderr, "both cgroup and no-aggregation "
741 "modes only available in system-wide mode\n");
742
f5b4a9c3 743 usage_with_options(stat_usage, options);
023695d9 744 }
f5b4a9c3 745
c3043569 746 /* Set attrs and nr_counters if no event is selected and !null_run */
361c99a6 747 if (!null_run && !evsel_list->nr_entries) {
69aad6f1
ACM
748 size_t c;
749
69aad6f1 750 for (c = 0; c < ARRAY_SIZE(default_attrs); ++c) {
361c99a6 751 pos = perf_evsel__new(&default_attrs[c], c);
69aad6f1
ACM
752 if (pos == NULL)
753 goto out;
361c99a6 754 perf_evlist__add(evsel_list, pos);
69aad6f1 755 }
c3043569 756 }
ddcacfa0 757
5c98d466
ACM
758 if (target_pid != -1)
759 target_tid = target_pid;
760
7e2ed097
ACM
761 evsel_list->threads = thread_map__new(target_pid, target_tid);
762 if (evsel_list->threads == NULL) {
5c98d466
ACM
763 pr_err("Problems finding threads of monitor\n");
764 usage_with_options(stat_usage, options);
765 }
766
a12b51c4 767 if (system_wide)
7e2ed097 768 evsel_list->cpus = cpu_map__new(cpu_list);
a12b51c4 769 else
7e2ed097 770 evsel_list->cpus = cpu_map__dummy_new();
ddcacfa0 771
7e2ed097 772 if (evsel_list->cpus == NULL) {
60d567e2 773 perror("failed to parse CPUs map");
c45c6ea2 774 usage_with_options(stat_usage, options);
60d567e2
ACM
775 return -1;
776 }
c45c6ea2 777
361c99a6 778 list_for_each_entry(pos, &evsel_list->entries, node) {
c52b12ed 779 if (perf_evsel__alloc_stat_priv(pos) < 0 ||
7e2ed097
ACM
780 perf_evsel__alloc_counts(pos, evsel_list->cpus->nr) < 0 ||
781 perf_evsel__alloc_fd(pos, evsel_list->cpus->nr, evsel_list->threads->nr) < 0)
69aad6f1 782 goto out_free_fd;
d6d901c2
ZY
783 }
784
58d7e993
IM
785 /*
786 * We dont want to block the signals - that would cause
787 * child tasks to inherit that and Ctrl-C would not work.
788 * What we want is for Ctrl-C to work in the exec()-ed
789 * task, but being ignored by perf stat itself:
790 */
f7b7c26e 791 atexit(sig_atexit);
58d7e993
IM
792 signal(SIGINT, skip_signal);
793 signal(SIGALRM, skip_signal);
794 signal(SIGABRT, skip_signal);
795
42202dd5
IM
796 status = 0;
797 for (run_idx = 0; run_idx < run_count; run_idx++) {
798 if (run_count != 1 && verbose)
3d632595 799 fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
42202dd5
IM
800 status = run_perf_stat(argc, argv);
801 }
802
084ab9f8
ACM
803 if (status != -1)
804 print_stat(argc, argv);
69aad6f1 805out_free_fd:
361c99a6 806 list_for_each_entry(pos, &evsel_list->entries, node)
69aad6f1 807 perf_evsel__free_stat_priv(pos);
7e2ed097 808 perf_evlist__delete_maps(evsel_list);
0015e2e1
ACM
809out:
810 perf_evlist__delete(evsel_list);
42202dd5 811 return status;
ddcacfa0 812}