builtin-stat.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. /*
  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:
  8. $ perf stat ~/hackbench 10
  9. Time: 0.104
  10. Performance counter stats for '/home/mingo/hackbench':
  11. 1255.538611 task clock ticks # 10.143 CPU utilization factor
  12. 54011 context switches # 0.043 M/sec
  13. 385 CPU migrations # 0.000 M/sec
  14. 17755 pagefaults # 0.014 M/sec
  15. 3808323185 CPU cycles # 3033.219 M/sec
  16. 1575111190 instructions # 1254.530 M/sec
  17. 17367895 cache references # 13.833 M/sec
  18. 7674421 cache misses # 6.112 M/sec
  19. Wall-clock time elapsed: 123.786620 msecs
  20. *
  21. * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
  22. *
  23. * Improvements and fixes by:
  24. *
  25. * Arjan van de Ven <arjan@linux.intel.com>
  26. * Yanmin Zhang <yanmin.zhang@intel.com>
  27. * Wu Fengguang <fengguang.wu@intel.com>
  28. * Mike Galbraith <efault@gmx.de>
  29. * Paul Mackerras <paulus@samba.org>
  30. * Jaswinder Singh Rajput <jaswinder@kernel.org>
  31. *
  32. * Released under the GPL v2. (and only v2, not any later version)
  33. */
  34. #include "perf.h"
  35. #include "builtin.h"
  36. #include "util/util.h"
  37. #include "util/parse-options.h"
  38. #include "util/parse-events.h"
  39. #include "util/event.h"
  40. #include "util/evlist.h"
  41. #include "util/evsel.h"
  42. #include "util/debug.h"
  43. #include "util/color.h"
  44. #include "util/header.h"
  45. #include "util/cpumap.h"
  46. #include "util/thread.h"
  47. #include "util/thread_map.h"
  48. #include <sys/prctl.h>
  49. #include <math.h>
  50. #include <locale.h>
  51. #define DEFAULT_SEPARATOR " "
  52. static struct perf_event_attr default_attrs[] = {
  53. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
  54. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
  55. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
  56. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
  57. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
  58. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES },
  59. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
  60. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
  61. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
  62. };
  63. struct perf_evlist *evsel_list;
  64. static bool system_wide = false;
  65. static int run_idx = 0;
  66. static int run_count = 1;
  67. static bool no_inherit = false;
  68. static bool scale = true;
  69. static bool no_aggr = false;
  70. static pid_t target_pid = -1;
  71. static pid_t target_tid = -1;
  72. static pid_t child_pid = -1;
  73. static bool null_run = false;
  74. static bool big_num = true;
  75. static int big_num_opt = -1;
  76. static const char *cpu_list;
  77. static const char *csv_sep = NULL;
  78. static bool csv_output = false;
  79. static volatile int done = 0;
  80. struct stats
  81. {
  82. double n, mean, M2;
  83. };
  84. struct perf_stat {
  85. struct stats res_stats[3];
  86. };
  87. static int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel)
  88. {
  89. evsel->priv = zalloc(sizeof(struct perf_stat));
  90. return evsel->priv == NULL ? -ENOMEM : 0;
  91. }
  92. static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
  93. {
  94. free(evsel->priv);
  95. evsel->priv = NULL;
  96. }
  97. static void update_stats(struct stats *stats, u64 val)
  98. {
  99. double delta;
  100. stats->n++;
  101. delta = val - stats->mean;
  102. stats->mean += delta / stats->n;
  103. stats->M2 += delta*(val - stats->mean);
  104. }
  105. static double avg_stats(struct stats *stats)
  106. {
  107. return stats->mean;
  108. }
  109. /*
  110. * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  111. *
  112. * (\Sum n_i^2) - ((\Sum n_i)^2)/n
  113. * s^2 = -------------------------------
  114. * n - 1
  115. *
  116. * http://en.wikipedia.org/wiki/Stddev
  117. *
  118. * The std dev of the mean is related to the std dev by:
  119. *
  120. * s
  121. * s_mean = -------
  122. * sqrt(n)
  123. *
  124. */
  125. static double stddev_stats(struct stats *stats)
  126. {
  127. double variance = stats->M2 / (stats->n - 1);
  128. double variance_mean = variance / stats->n;
  129. return sqrt(variance_mean);
  130. }
  131. struct stats runtime_nsecs_stats[MAX_NR_CPUS];
  132. struct stats runtime_cycles_stats[MAX_NR_CPUS];
  133. struct stats runtime_stalled_cycles_stats[MAX_NR_CPUS];
  134. struct stats runtime_branches_stats[MAX_NR_CPUS];
  135. struct stats runtime_cacherefs_stats[MAX_NR_CPUS];
  136. struct stats walltime_nsecs_stats;
  137. static int create_perf_stat_counter(struct perf_evsel *evsel)
  138. {
  139. struct perf_event_attr *attr = &evsel->attr;
  140. if (scale)
  141. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  142. PERF_FORMAT_TOTAL_TIME_RUNNING;
  143. attr->inherit = !no_inherit;
  144. if (system_wide)
  145. return perf_evsel__open_per_cpu(evsel, evsel_list->cpus, false);
  146. if (target_pid == -1 && target_tid == -1) {
  147. attr->disabled = 1;
  148. attr->enable_on_exec = 1;
  149. }
  150. return perf_evsel__open_per_thread(evsel, evsel_list->threads, false);
  151. }
  152. /*
  153. * Does the counter have nsecs as a unit?
  154. */
  155. static inline int nsec_counter(struct perf_evsel *evsel)
  156. {
  157. if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
  158. perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
  159. return 1;
  160. return 0;
  161. }
  162. /*
  163. * Update various tracking values we maintain to print
  164. * more semantic information such as miss/hit ratios,
  165. * instruction rates, etc:
  166. */
  167. static void update_shadow_stats(struct perf_evsel *counter, u64 *count)
  168. {
  169. if (perf_evsel__match(counter, SOFTWARE, SW_TASK_CLOCK))
  170. update_stats(&runtime_nsecs_stats[0], count[0]);
  171. else if (perf_evsel__match(counter, HARDWARE, HW_CPU_CYCLES))
  172. update_stats(&runtime_cycles_stats[0], count[0]);
  173. else if (perf_evsel__match(counter, HARDWARE, HW_STALLED_CYCLES))
  174. update_stats(&runtime_stalled_cycles_stats[0], count[0]);
  175. else if (perf_evsel__match(counter, HARDWARE, HW_BRANCH_INSTRUCTIONS))
  176. update_stats(&runtime_branches_stats[0], count[0]);
  177. else if (perf_evsel__match(counter, HARDWARE, HW_CACHE_REFERENCES))
  178. update_stats(&runtime_cacherefs_stats[0], count[0]);
  179. }
  180. /*
  181. * Read out the results of a single counter:
  182. * aggregate counts across CPUs in system-wide mode
  183. */
  184. static int read_counter_aggr(struct perf_evsel *counter)
  185. {
  186. struct perf_stat *ps = counter->priv;
  187. u64 *count = counter->counts->aggr.values;
  188. int i;
  189. if (__perf_evsel__read(counter, evsel_list->cpus->nr,
  190. evsel_list->threads->nr, scale) < 0)
  191. return -1;
  192. for (i = 0; i < 3; i++)
  193. update_stats(&ps->res_stats[i], count[i]);
  194. if (verbose) {
  195. fprintf(stderr, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
  196. event_name(counter), count[0], count[1], count[2]);
  197. }
  198. /*
  199. * Save the full runtime - to allow normalization during printout:
  200. */
  201. update_shadow_stats(counter, count);
  202. return 0;
  203. }
  204. /*
  205. * Read out the results of a single counter:
  206. * do not aggregate counts across CPUs in system-wide mode
  207. */
  208. static int read_counter(struct perf_evsel *counter)
  209. {
  210. u64 *count;
  211. int cpu;
  212. for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
  213. if (__perf_evsel__read_on_cpu(counter, cpu, 0, scale) < 0)
  214. return -1;
  215. count = counter->counts->cpu[cpu].values;
  216. update_shadow_stats(counter, count);
  217. }
  218. return 0;
  219. }
  220. static int run_perf_stat(int argc __used, const char **argv)
  221. {
  222. unsigned long long t0, t1;
  223. struct perf_evsel *counter;
  224. int status = 0;
  225. int child_ready_pipe[2], go_pipe[2];
  226. const bool forks = (argc > 0);
  227. char buf;
  228. if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
  229. perror("failed to create pipes");
  230. exit(1);
  231. }
  232. if (forks) {
  233. if ((child_pid = fork()) < 0)
  234. perror("failed to fork");
  235. if (!child_pid) {
  236. close(child_ready_pipe[0]);
  237. close(go_pipe[1]);
  238. fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
  239. /*
  240. * Do a dummy execvp to get the PLT entry resolved,
  241. * so we avoid the resolver overhead on the real
  242. * execvp call.
  243. */
  244. execvp("", (char **)argv);
  245. /*
  246. * Tell the parent we're ready to go
  247. */
  248. close(child_ready_pipe[1]);
  249. /*
  250. * Wait until the parent tells us to go.
  251. */
  252. if (read(go_pipe[0], &buf, 1) == -1)
  253. perror("unable to read pipe");
  254. execvp(argv[0], (char **)argv);
  255. perror(argv[0]);
  256. exit(-1);
  257. }
  258. if (target_tid == -1 && target_pid == -1 && !system_wide)
  259. evsel_list->threads->map[0] = child_pid;
  260. /*
  261. * Wait for the child to be ready to exec.
  262. */
  263. close(child_ready_pipe[1]);
  264. close(go_pipe[0]);
  265. if (read(child_ready_pipe[0], &buf, 1) == -1)
  266. perror("unable to read pipe");
  267. close(child_ready_pipe[0]);
  268. }
  269. list_for_each_entry(counter, &evsel_list->entries, node) {
  270. if (create_perf_stat_counter(counter) < 0) {
  271. if (errno == -EPERM || errno == -EACCES) {
  272. error("You may not have permission to collect %sstats.\n"
  273. "\t Consider tweaking"
  274. " /proc/sys/kernel/perf_event_paranoid or running as root.",
  275. system_wide ? "system-wide " : "");
  276. } else if (errno == ENOENT) {
  277. error("%s event is not supported. ", event_name(counter));
  278. } else {
  279. error("open_counter returned with %d (%s). "
  280. "/bin/dmesg may provide additional information.\n",
  281. errno, strerror(errno));
  282. }
  283. if (child_pid != -1)
  284. kill(child_pid, SIGTERM);
  285. die("Not all events could be opened.\n");
  286. return -1;
  287. }
  288. }
  289. if (perf_evlist__set_filters(evsel_list)) {
  290. error("failed to set filter with %d (%s)\n", errno,
  291. strerror(errno));
  292. return -1;
  293. }
  294. /*
  295. * Enable counters and exec the command:
  296. */
  297. t0 = rdclock();
  298. if (forks) {
  299. close(go_pipe[1]);
  300. wait(&status);
  301. } else {
  302. while(!done) sleep(1);
  303. }
  304. t1 = rdclock();
  305. update_stats(&walltime_nsecs_stats, t1 - t0);
  306. if (no_aggr) {
  307. list_for_each_entry(counter, &evsel_list->entries, node) {
  308. read_counter(counter);
  309. perf_evsel__close_fd(counter, evsel_list->cpus->nr, 1);
  310. }
  311. } else {
  312. list_for_each_entry(counter, &evsel_list->entries, node) {
  313. read_counter_aggr(counter);
  314. perf_evsel__close_fd(counter, evsel_list->cpus->nr,
  315. evsel_list->threads->nr);
  316. }
  317. }
  318. return WEXITSTATUS(status);
  319. }
  320. static void print_noise_pct(double total, double avg)
  321. {
  322. double pct = 0.0;
  323. if (avg)
  324. pct = 100.0*total/avg;
  325. fprintf(stderr, " ( +-%6.2f%% )", pct);
  326. }
  327. static void print_noise(struct perf_evsel *evsel, double avg)
  328. {
  329. struct perf_stat *ps;
  330. if (run_count == 1)
  331. return;
  332. ps = evsel->priv;
  333. print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
  334. }
  335. static void nsec_printout(int cpu, struct perf_evsel *evsel, double avg)
  336. {
  337. double msecs = avg / 1e6;
  338. char cpustr[16] = { '\0', };
  339. const char *fmt = csv_output ? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
  340. if (no_aggr)
  341. sprintf(cpustr, "CPU%*d%s",
  342. csv_output ? 0 : -4,
  343. evsel_list->cpus->map[cpu], csv_sep);
  344. fprintf(stderr, fmt, cpustr, msecs, csv_sep, event_name(evsel));
  345. if (evsel->cgrp)
  346. fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
  347. if (csv_output)
  348. return;
  349. if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
  350. fprintf(stderr, " # %8.3f CPUs utilized ", avg / avg_stats(&walltime_nsecs_stats));
  351. }
  352. static void print_stalled_cycles(int cpu, struct perf_evsel *evsel __used, double avg)
  353. {
  354. double total, ratio = 0.0;
  355. const char *color;
  356. total = avg_stats(&runtime_cycles_stats[cpu]);
  357. if (total)
  358. ratio = avg / total * 100.0;
  359. color = PERF_COLOR_NORMAL;
  360. if (ratio > 75.0)
  361. color = PERF_COLOR_RED;
  362. else if (ratio > 50.0)
  363. color = PERF_COLOR_MAGENTA;
  364. else if (ratio > 25.0)
  365. color = PERF_COLOR_YELLOW;
  366. fprintf(stderr, " # ");
  367. color_fprintf(stderr, color, "%5.2f%%", ratio);
  368. fprintf(stderr, " of all cycles are idle ");
  369. }
  370. static void print_branch_misses(int cpu, struct perf_evsel *evsel __used, double avg)
  371. {
  372. double total, ratio = 0.0;
  373. const char *color;
  374. total = avg_stats(&runtime_branches_stats[cpu]);
  375. if (total)
  376. ratio = avg / total * 100.0;
  377. color = PERF_COLOR_NORMAL;
  378. if (ratio > 20.0)
  379. color = PERF_COLOR_RED;
  380. else if (ratio > 10.0)
  381. color = PERF_COLOR_MAGENTA;
  382. else if (ratio > 5.0)
  383. color = PERF_COLOR_YELLOW;
  384. fprintf(stderr, " # ");
  385. color_fprintf(stderr, color, "%5.2f%%", ratio);
  386. fprintf(stderr, " of all branches ");
  387. }
  388. static void abs_printout(int cpu, struct perf_evsel *evsel, double avg)
  389. {
  390. double total, ratio = 0.0;
  391. char cpustr[16] = { '\0', };
  392. const char *fmt;
  393. if (csv_output)
  394. fmt = "%s%.0f%s%s";
  395. else if (big_num)
  396. fmt = "%s%'18.0f%s%-24s";
  397. else
  398. fmt = "%s%18.0f%s%-24s";
  399. if (no_aggr)
  400. sprintf(cpustr, "CPU%*d%s",
  401. csv_output ? 0 : -4,
  402. evsel_list->cpus->map[cpu], csv_sep);
  403. else
  404. cpu = 0;
  405. fprintf(stderr, fmt, cpustr, avg, csv_sep, event_name(evsel));
  406. if (evsel->cgrp)
  407. fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
  408. if (csv_output)
  409. return;
  410. if (perf_evsel__match(evsel, HARDWARE, HW_INSTRUCTIONS)) {
  411. total = avg_stats(&runtime_cycles_stats[cpu]);
  412. if (total)
  413. ratio = avg / total;
  414. fprintf(stderr, " # %4.2f insns per cycle", ratio);
  415. total = avg_stats(&runtime_stalled_cycles_stats[cpu]);
  416. if (total && avg) {
  417. ratio = total / avg;
  418. fprintf(stderr, "\n # %4.2f stalled cycles per insn", ratio);
  419. }
  420. } else if (perf_evsel__match(evsel, HARDWARE, HW_BRANCH_MISSES) &&
  421. runtime_branches_stats[cpu].n != 0) {
  422. print_branch_misses(cpu, evsel, avg);
  423. } else if (perf_evsel__match(evsel, HARDWARE, HW_CACHE_MISSES) &&
  424. runtime_cacherefs_stats[cpu].n != 0) {
  425. total = avg_stats(&runtime_cacherefs_stats[cpu]);
  426. if (total)
  427. ratio = avg * 100 / total;
  428. fprintf(stderr, " # %8.3f %% of all cache refs ", ratio);
  429. } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES)) {
  430. print_stalled_cycles(cpu, evsel, avg);
  431. } else if (perf_evsel__match(evsel, HARDWARE, HW_CPU_CYCLES)) {
  432. total = avg_stats(&runtime_nsecs_stats[cpu]);
  433. if (total)
  434. ratio = 1.0 * avg / total;
  435. fprintf(stderr, " # %8.3f GHz ", ratio);
  436. } else if (runtime_nsecs_stats[cpu].n != 0) {
  437. total = avg_stats(&runtime_nsecs_stats[cpu]);
  438. if (total)
  439. ratio = 1000.0 * avg / total;
  440. fprintf(stderr, " # %8.3f M/sec ", ratio);
  441. } else {
  442. fprintf(stderr, " ");
  443. }
  444. }
  445. /*
  446. * Print out the results of a single counter:
  447. * aggregated counts in system-wide mode
  448. */
  449. static void print_counter_aggr(struct perf_evsel *counter)
  450. {
  451. struct perf_stat *ps = counter->priv;
  452. double avg = avg_stats(&ps->res_stats[0]);
  453. int scaled = counter->counts->scaled;
  454. if (scaled == -1) {
  455. fprintf(stderr, "%*s%s%*s",
  456. csv_output ? 0 : 18,
  457. "<not counted>",
  458. csv_sep,
  459. csv_output ? 0 : -24,
  460. event_name(counter));
  461. if (counter->cgrp)
  462. fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
  463. fputc('\n', stderr);
  464. return;
  465. }
  466. if (nsec_counter(counter))
  467. nsec_printout(-1, counter, avg);
  468. else
  469. abs_printout(-1, counter, avg);
  470. if (csv_output) {
  471. fputc('\n', stderr);
  472. return;
  473. }
  474. print_noise(counter, avg);
  475. if (scaled) {
  476. double avg_enabled, avg_running;
  477. avg_enabled = avg_stats(&ps->res_stats[1]);
  478. avg_running = avg_stats(&ps->res_stats[2]);
  479. fprintf(stderr, " (scaled from %.2f%%)",
  480. 100 * avg_running / avg_enabled);
  481. }
  482. fprintf(stderr, "\n");
  483. }
  484. /*
  485. * Print out the results of a single counter:
  486. * does not use aggregated count in system-wide
  487. */
  488. static void print_counter(struct perf_evsel *counter)
  489. {
  490. u64 ena, run, val;
  491. int cpu;
  492. for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
  493. val = counter->counts->cpu[cpu].val;
  494. ena = counter->counts->cpu[cpu].ena;
  495. run = counter->counts->cpu[cpu].run;
  496. if (run == 0 || ena == 0) {
  497. fprintf(stderr, "CPU%*d%s%*s%s%*s",
  498. csv_output ? 0 : -4,
  499. evsel_list->cpus->map[cpu], csv_sep,
  500. csv_output ? 0 : 18,
  501. "<not counted>", csv_sep,
  502. csv_output ? 0 : -24,
  503. event_name(counter));
  504. if (counter->cgrp)
  505. fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
  506. fputc('\n', stderr);
  507. continue;
  508. }
  509. if (nsec_counter(counter))
  510. nsec_printout(cpu, counter, val);
  511. else
  512. abs_printout(cpu, counter, val);
  513. if (!csv_output) {
  514. print_noise(counter, 1.0);
  515. if (run != ena) {
  516. fprintf(stderr, " (scaled from %.2f%%)",
  517. 100.0 * run / ena);
  518. }
  519. }
  520. fputc('\n', stderr);
  521. }
  522. }
  523. static void print_stat(int argc, const char **argv)
  524. {
  525. struct perf_evsel *counter;
  526. int i;
  527. fflush(stdout);
  528. if (!csv_output) {
  529. fprintf(stderr, "\n");
  530. fprintf(stderr, " Performance counter stats for ");
  531. if(target_pid == -1 && target_tid == -1) {
  532. fprintf(stderr, "\'%s", argv[0]);
  533. for (i = 1; i < argc; i++)
  534. fprintf(stderr, " %s", argv[i]);
  535. } else if (target_pid != -1)
  536. fprintf(stderr, "process id \'%d", target_pid);
  537. else
  538. fprintf(stderr, "thread id \'%d", target_tid);
  539. fprintf(stderr, "\'");
  540. if (run_count > 1)
  541. fprintf(stderr, " (%d runs)", run_count);
  542. fprintf(stderr, ":\n\n");
  543. }
  544. if (no_aggr) {
  545. list_for_each_entry(counter, &evsel_list->entries, node)
  546. print_counter(counter);
  547. } else {
  548. list_for_each_entry(counter, &evsel_list->entries, node)
  549. print_counter_aggr(counter);
  550. }
  551. if (!csv_output) {
  552. fprintf(stderr, "\n");
  553. fprintf(stderr, " %18.9f seconds time elapsed",
  554. avg_stats(&walltime_nsecs_stats)/1e9);
  555. if (run_count > 1) {
  556. print_noise_pct(stddev_stats(&walltime_nsecs_stats),
  557. avg_stats(&walltime_nsecs_stats));
  558. }
  559. fprintf(stderr, "\n\n");
  560. }
  561. }
  562. static volatile int signr = -1;
  563. static void skip_signal(int signo)
  564. {
  565. if(child_pid == -1)
  566. done = 1;
  567. signr = signo;
  568. }
  569. static void sig_atexit(void)
  570. {
  571. if (child_pid != -1)
  572. kill(child_pid, SIGTERM);
  573. if (signr == -1)
  574. return;
  575. signal(signr, SIG_DFL);
  576. kill(getpid(), signr);
  577. }
  578. static const char * const stat_usage[] = {
  579. "perf stat [<options>] [<command>]",
  580. NULL
  581. };
  582. static int stat__set_big_num(const struct option *opt __used,
  583. const char *s __used, int unset)
  584. {
  585. big_num_opt = unset ? 0 : 1;
  586. return 0;
  587. }
  588. static const struct option options[] = {
  589. OPT_CALLBACK('e', "event", &evsel_list, "event",
  590. "event selector. use 'perf list' to list available events",
  591. parse_events),
  592. OPT_CALLBACK(0, "filter", &evsel_list, "filter",
  593. "event filter", parse_filter),
  594. OPT_BOOLEAN('i', "no-inherit", &no_inherit,
  595. "child tasks do not inherit counters"),
  596. OPT_INTEGER('p', "pid", &target_pid,
  597. "stat events on existing process id"),
  598. OPT_INTEGER('t', "tid", &target_tid,
  599. "stat events on existing thread id"),
  600. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  601. "system-wide collection from all CPUs"),
  602. OPT_BOOLEAN('c', "scale", &scale,
  603. "scale/normalize counters"),
  604. OPT_INCR('v', "verbose", &verbose,
  605. "be more verbose (show counter open errors, etc)"),
  606. OPT_INTEGER('r', "repeat", &run_count,
  607. "repeat command and print average + stddev (max: 100)"),
  608. OPT_BOOLEAN('n', "null", &null_run,
  609. "null run - dont start any counters"),
  610. OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
  611. "print large numbers with thousands\' separators",
  612. stat__set_big_num),
  613. OPT_STRING('C', "cpu", &cpu_list, "cpu",
  614. "list of cpus to monitor in system-wide"),
  615. OPT_BOOLEAN('A', "no-aggr", &no_aggr,
  616. "disable CPU count aggregation"),
  617. OPT_STRING('x', "field-separator", &csv_sep, "separator",
  618. "print counts with custom separator"),
  619. OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
  620. "monitor event in cgroup name only",
  621. parse_cgroups),
  622. OPT_END()
  623. };
  624. int cmd_stat(int argc, const char **argv, const char *prefix __used)
  625. {
  626. struct perf_evsel *pos;
  627. int status = -ENOMEM;
  628. setlocale(LC_ALL, "");
  629. evsel_list = perf_evlist__new(NULL, NULL);
  630. if (evsel_list == NULL)
  631. return -ENOMEM;
  632. argc = parse_options(argc, argv, options, stat_usage,
  633. PARSE_OPT_STOP_AT_NON_OPTION);
  634. if (csv_sep)
  635. csv_output = true;
  636. else
  637. csv_sep = DEFAULT_SEPARATOR;
  638. /*
  639. * let the spreadsheet do the pretty-printing
  640. */
  641. if (csv_output) {
  642. /* User explicitely passed -B? */
  643. if (big_num_opt == 1) {
  644. fprintf(stderr, "-B option not supported with -x\n");
  645. usage_with_options(stat_usage, options);
  646. } else /* Nope, so disable big number formatting */
  647. big_num = false;
  648. } else if (big_num_opt == 0) /* User passed --no-big-num */
  649. big_num = false;
  650. if (!argc && target_pid == -1 && target_tid == -1)
  651. usage_with_options(stat_usage, options);
  652. if (run_count <= 0)
  653. usage_with_options(stat_usage, options);
  654. /* no_aggr, cgroup are for system-wide only */
  655. if ((no_aggr || nr_cgroups) && !system_wide) {
  656. fprintf(stderr, "both cgroup and no-aggregation "
  657. "modes only available in system-wide mode\n");
  658. usage_with_options(stat_usage, options);
  659. }
  660. /* Set attrs and nr_counters if no event is selected and !null_run */
  661. if (!null_run && !evsel_list->nr_entries) {
  662. size_t c;
  663. for (c = 0; c < ARRAY_SIZE(default_attrs); ++c) {
  664. pos = perf_evsel__new(&default_attrs[c], c);
  665. if (pos == NULL)
  666. goto out;
  667. perf_evlist__add(evsel_list, pos);
  668. }
  669. }
  670. if (target_pid != -1)
  671. target_tid = target_pid;
  672. evsel_list->threads = thread_map__new(target_pid, target_tid);
  673. if (evsel_list->threads == NULL) {
  674. pr_err("Problems finding threads of monitor\n");
  675. usage_with_options(stat_usage, options);
  676. }
  677. if (system_wide)
  678. evsel_list->cpus = cpu_map__new(cpu_list);
  679. else
  680. evsel_list->cpus = cpu_map__dummy_new();
  681. if (evsel_list->cpus == NULL) {
  682. perror("failed to parse CPUs map");
  683. usage_with_options(stat_usage, options);
  684. return -1;
  685. }
  686. list_for_each_entry(pos, &evsel_list->entries, node) {
  687. if (perf_evsel__alloc_stat_priv(pos) < 0 ||
  688. perf_evsel__alloc_counts(pos, evsel_list->cpus->nr) < 0 ||
  689. perf_evsel__alloc_fd(pos, evsel_list->cpus->nr, evsel_list->threads->nr) < 0)
  690. goto out_free_fd;
  691. }
  692. /*
  693. * We dont want to block the signals - that would cause
  694. * child tasks to inherit that and Ctrl-C would not work.
  695. * What we want is for Ctrl-C to work in the exec()-ed
  696. * task, but being ignored by perf stat itself:
  697. */
  698. atexit(sig_atexit);
  699. signal(SIGINT, skip_signal);
  700. signal(SIGALRM, skip_signal);
  701. signal(SIGABRT, skip_signal);
  702. status = 0;
  703. for (run_idx = 0; run_idx < run_count; run_idx++) {
  704. if (run_count != 1 && verbose)
  705. fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
  706. status = run_perf_stat(argc, argv);
  707. }
  708. if (status != -1)
  709. print_stat(argc, argv);
  710. out_free_fd:
  711. list_for_each_entry(pos, &evsel_list->entries, node)
  712. perf_evsel__free_stat_priv(pos);
  713. perf_evlist__delete_maps(evsel_list);
  714. out:
  715. perf_evlist__delete(evsel_list);
  716. return status;
  717. }