builtin-stat.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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 runtime_l1_dcache_stats[MAX_NR_CPUS];
  137. struct stats walltime_nsecs_stats;
  138. static int create_perf_stat_counter(struct perf_evsel *evsel)
  139. {
  140. struct perf_event_attr *attr = &evsel->attr;
  141. if (scale)
  142. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  143. PERF_FORMAT_TOTAL_TIME_RUNNING;
  144. attr->inherit = !no_inherit;
  145. if (system_wide)
  146. return perf_evsel__open_per_cpu(evsel, evsel_list->cpus, false);
  147. if (target_pid == -1 && target_tid == -1) {
  148. attr->disabled = 1;
  149. attr->enable_on_exec = 1;
  150. }
  151. return perf_evsel__open_per_thread(evsel, evsel_list->threads, false);
  152. }
  153. /*
  154. * Does the counter have nsecs as a unit?
  155. */
  156. static inline int nsec_counter(struct perf_evsel *evsel)
  157. {
  158. if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) ||
  159. perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
  160. return 1;
  161. return 0;
  162. }
  163. /*
  164. * Update various tracking values we maintain to print
  165. * more semantic information such as miss/hit ratios,
  166. * instruction rates, etc:
  167. */
  168. static void update_shadow_stats(struct perf_evsel *counter, u64 *count)
  169. {
  170. if (perf_evsel__match(counter, SOFTWARE, SW_TASK_CLOCK))
  171. update_stats(&runtime_nsecs_stats[0], count[0]);
  172. else if (perf_evsel__match(counter, HARDWARE, HW_CPU_CYCLES))
  173. update_stats(&runtime_cycles_stats[0], count[0]);
  174. else if (perf_evsel__match(counter, HARDWARE, HW_STALLED_CYCLES))
  175. update_stats(&runtime_stalled_cycles_stats[0], count[0]);
  176. else if (perf_evsel__match(counter, HARDWARE, HW_BRANCH_INSTRUCTIONS))
  177. update_stats(&runtime_branches_stats[0], count[0]);
  178. else if (perf_evsel__match(counter, HARDWARE, HW_CACHE_REFERENCES))
  179. update_stats(&runtime_cacherefs_stats[0], count[0]);
  180. else if (perf_evsel__match(counter, HW_CACHE, HW_CACHE_L1D))
  181. update_stats(&runtime_l1_dcache_stats[0], count[0]);
  182. }
  183. /*
  184. * Read out the results of a single counter:
  185. * aggregate counts across CPUs in system-wide mode
  186. */
  187. static int read_counter_aggr(struct perf_evsel *counter)
  188. {
  189. struct perf_stat *ps = counter->priv;
  190. u64 *count = counter->counts->aggr.values;
  191. int i;
  192. if (__perf_evsel__read(counter, evsel_list->cpus->nr,
  193. evsel_list->threads->nr, scale) < 0)
  194. return -1;
  195. for (i = 0; i < 3; i++)
  196. update_stats(&ps->res_stats[i], count[i]);
  197. if (verbose) {
  198. fprintf(stderr, "%s: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
  199. event_name(counter), count[0], count[1], count[2]);
  200. }
  201. /*
  202. * Save the full runtime - to allow normalization during printout:
  203. */
  204. update_shadow_stats(counter, count);
  205. return 0;
  206. }
  207. /*
  208. * Read out the results of a single counter:
  209. * do not aggregate counts across CPUs in system-wide mode
  210. */
  211. static int read_counter(struct perf_evsel *counter)
  212. {
  213. u64 *count;
  214. int cpu;
  215. for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
  216. if (__perf_evsel__read_on_cpu(counter, cpu, 0, scale) < 0)
  217. return -1;
  218. count = counter->counts->cpu[cpu].values;
  219. update_shadow_stats(counter, count);
  220. }
  221. return 0;
  222. }
  223. static int run_perf_stat(int argc __used, const char **argv)
  224. {
  225. unsigned long long t0, t1;
  226. struct perf_evsel *counter;
  227. int status = 0;
  228. int child_ready_pipe[2], go_pipe[2];
  229. const bool forks = (argc > 0);
  230. char buf;
  231. if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
  232. perror("failed to create pipes");
  233. exit(1);
  234. }
  235. if (forks) {
  236. if ((child_pid = fork()) < 0)
  237. perror("failed to fork");
  238. if (!child_pid) {
  239. close(child_ready_pipe[0]);
  240. close(go_pipe[1]);
  241. fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
  242. /*
  243. * Do a dummy execvp to get the PLT entry resolved,
  244. * so we avoid the resolver overhead on the real
  245. * execvp call.
  246. */
  247. execvp("", (char **)argv);
  248. /*
  249. * Tell the parent we're ready to go
  250. */
  251. close(child_ready_pipe[1]);
  252. /*
  253. * Wait until the parent tells us to go.
  254. */
  255. if (read(go_pipe[0], &buf, 1) == -1)
  256. perror("unable to read pipe");
  257. execvp(argv[0], (char **)argv);
  258. perror(argv[0]);
  259. exit(-1);
  260. }
  261. if (target_tid == -1 && target_pid == -1 && !system_wide)
  262. evsel_list->threads->map[0] = child_pid;
  263. /*
  264. * Wait for the child to be ready to exec.
  265. */
  266. close(child_ready_pipe[1]);
  267. close(go_pipe[0]);
  268. if (read(child_ready_pipe[0], &buf, 1) == -1)
  269. perror("unable to read pipe");
  270. close(child_ready_pipe[0]);
  271. }
  272. list_for_each_entry(counter, &evsel_list->entries, node) {
  273. if (create_perf_stat_counter(counter) < 0) {
  274. if (errno == -EPERM || errno == -EACCES) {
  275. error("You may not have permission to collect %sstats.\n"
  276. "\t Consider tweaking"
  277. " /proc/sys/kernel/perf_event_paranoid or running as root.",
  278. system_wide ? "system-wide " : "");
  279. } else if (errno == ENOENT) {
  280. error("%s event is not supported. ", event_name(counter));
  281. } else {
  282. error("open_counter returned with %d (%s). "
  283. "/bin/dmesg may provide additional information.\n",
  284. errno, strerror(errno));
  285. }
  286. if (child_pid != -1)
  287. kill(child_pid, SIGTERM);
  288. die("Not all events could be opened.\n");
  289. return -1;
  290. }
  291. }
  292. if (perf_evlist__set_filters(evsel_list)) {
  293. error("failed to set filter with %d (%s)\n", errno,
  294. strerror(errno));
  295. return -1;
  296. }
  297. /*
  298. * Enable counters and exec the command:
  299. */
  300. t0 = rdclock();
  301. if (forks) {
  302. close(go_pipe[1]);
  303. wait(&status);
  304. } else {
  305. while(!done) sleep(1);
  306. }
  307. t1 = rdclock();
  308. update_stats(&walltime_nsecs_stats, t1 - t0);
  309. if (no_aggr) {
  310. list_for_each_entry(counter, &evsel_list->entries, node) {
  311. read_counter(counter);
  312. perf_evsel__close_fd(counter, evsel_list->cpus->nr, 1);
  313. }
  314. } else {
  315. list_for_each_entry(counter, &evsel_list->entries, node) {
  316. read_counter_aggr(counter);
  317. perf_evsel__close_fd(counter, evsel_list->cpus->nr,
  318. evsel_list->threads->nr);
  319. }
  320. }
  321. return WEXITSTATUS(status);
  322. }
  323. static void print_noise_pct(double total, double avg)
  324. {
  325. double pct = 0.0;
  326. if (avg)
  327. pct = 100.0*total/avg;
  328. fprintf(stderr, " ( +-%6.2f%% )", pct);
  329. }
  330. static void print_noise(struct perf_evsel *evsel, double avg)
  331. {
  332. struct perf_stat *ps;
  333. if (run_count == 1)
  334. return;
  335. ps = evsel->priv;
  336. print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
  337. }
  338. static void nsec_printout(int cpu, struct perf_evsel *evsel, double avg)
  339. {
  340. double msecs = avg / 1e6;
  341. char cpustr[16] = { '\0', };
  342. const char *fmt = csv_output ? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
  343. if (no_aggr)
  344. sprintf(cpustr, "CPU%*d%s",
  345. csv_output ? 0 : -4,
  346. evsel_list->cpus->map[cpu], csv_sep);
  347. fprintf(stderr, fmt, cpustr, msecs, csv_sep, event_name(evsel));
  348. if (evsel->cgrp)
  349. fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
  350. if (csv_output)
  351. return;
  352. if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
  353. fprintf(stderr, " # %8.3f CPUs utilized ", avg / avg_stats(&walltime_nsecs_stats));
  354. }
  355. static void print_stalled_cycles(int cpu, struct perf_evsel *evsel __used, double avg)
  356. {
  357. double total, ratio = 0.0;
  358. const char *color;
  359. total = avg_stats(&runtime_cycles_stats[cpu]);
  360. if (total)
  361. ratio = avg / total * 100.0;
  362. color = PERF_COLOR_NORMAL;
  363. if (ratio > 75.0)
  364. color = PERF_COLOR_RED;
  365. else if (ratio > 50.0)
  366. color = PERF_COLOR_MAGENTA;
  367. else if (ratio > 25.0)
  368. color = PERF_COLOR_YELLOW;
  369. fprintf(stderr, " # ");
  370. color_fprintf(stderr, color, "%5.2f%%", ratio);
  371. fprintf(stderr, " of all cycles are idle ");
  372. }
  373. static void print_branch_misses(int cpu, struct perf_evsel *evsel __used, double avg)
  374. {
  375. double total, ratio = 0.0;
  376. const char *color;
  377. total = avg_stats(&runtime_branches_stats[cpu]);
  378. if (total)
  379. ratio = avg / total * 100.0;
  380. color = PERF_COLOR_NORMAL;
  381. if (ratio > 20.0)
  382. color = PERF_COLOR_RED;
  383. else if (ratio > 10.0)
  384. color = PERF_COLOR_MAGENTA;
  385. else if (ratio > 5.0)
  386. color = PERF_COLOR_YELLOW;
  387. fprintf(stderr, " # ");
  388. color_fprintf(stderr, color, "%5.2f%%", ratio);
  389. fprintf(stderr, " of all branches ");
  390. }
  391. static void print_l1_dcache_misses(int cpu, struct perf_evsel *evsel __used, double avg)
  392. {
  393. double total, ratio = 0.0;
  394. const char *color;
  395. total = avg_stats(&runtime_l1_dcache_stats[cpu]);
  396. if (total)
  397. ratio = avg / total * 100.0;
  398. color = PERF_COLOR_NORMAL;
  399. if (ratio > 20.0)
  400. color = PERF_COLOR_RED;
  401. else if (ratio > 10.0)
  402. color = PERF_COLOR_MAGENTA;
  403. else if (ratio > 5.0)
  404. color = PERF_COLOR_YELLOW;
  405. fprintf(stderr, " # ");
  406. color_fprintf(stderr, color, "%5.2f%%", ratio);
  407. fprintf(stderr, " of all L1-dcache hits ");
  408. }
  409. static void abs_printout(int cpu, struct perf_evsel *evsel, double avg)
  410. {
  411. double total, ratio = 0.0;
  412. char cpustr[16] = { '\0', };
  413. const char *fmt;
  414. if (csv_output)
  415. fmt = "%s%.0f%s%s";
  416. else if (big_num)
  417. fmt = "%s%'18.0f%s%-24s";
  418. else
  419. fmt = "%s%18.0f%s%-24s";
  420. if (no_aggr)
  421. sprintf(cpustr, "CPU%*d%s",
  422. csv_output ? 0 : -4,
  423. evsel_list->cpus->map[cpu], csv_sep);
  424. else
  425. cpu = 0;
  426. fprintf(stderr, fmt, cpustr, avg, csv_sep, event_name(evsel));
  427. if (evsel->cgrp)
  428. fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
  429. if (csv_output)
  430. return;
  431. if (perf_evsel__match(evsel, HARDWARE, HW_INSTRUCTIONS)) {
  432. total = avg_stats(&runtime_cycles_stats[cpu]);
  433. if (total)
  434. ratio = avg / total;
  435. fprintf(stderr, " # %4.2f insns per cycle", ratio);
  436. total = avg_stats(&runtime_stalled_cycles_stats[cpu]);
  437. if (total && avg) {
  438. ratio = total / avg;
  439. fprintf(stderr, "\n # %4.2f stalled cycles per insn", ratio);
  440. }
  441. } else if (perf_evsel__match(evsel, HARDWARE, HW_BRANCH_MISSES) &&
  442. runtime_branches_stats[cpu].n != 0) {
  443. print_branch_misses(cpu, evsel, avg);
  444. } else if (
  445. evsel->attr.type == PERF_TYPE_HW_CACHE &&
  446. evsel->attr.config == ( PERF_COUNT_HW_CACHE_L1D |
  447. ((PERF_COUNT_HW_CACHE_OP_READ) << 8) |
  448. ((PERF_COUNT_HW_CACHE_RESULT_MISS) << 16)) &&
  449. runtime_branches_stats[cpu].n != 0) {
  450. print_l1_dcache_misses(cpu, evsel, avg);
  451. } else if (perf_evsel__match(evsel, HARDWARE, HW_CACHE_MISSES) &&
  452. runtime_cacherefs_stats[cpu].n != 0) {
  453. total = avg_stats(&runtime_cacherefs_stats[cpu]);
  454. if (total)
  455. ratio = avg * 100 / total;
  456. fprintf(stderr, " # %8.3f %% of all cache refs ", ratio);
  457. } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES)) {
  458. print_stalled_cycles(cpu, evsel, avg);
  459. } else if (perf_evsel__match(evsel, HARDWARE, HW_CPU_CYCLES)) {
  460. total = avg_stats(&runtime_nsecs_stats[cpu]);
  461. if (total)
  462. ratio = 1.0 * avg / total;
  463. fprintf(stderr, " # %8.3f GHz ", ratio);
  464. } else if (runtime_nsecs_stats[cpu].n != 0) {
  465. total = avg_stats(&runtime_nsecs_stats[cpu]);
  466. if (total)
  467. ratio = 1000.0 * avg / total;
  468. fprintf(stderr, " # %8.3f M/sec ", ratio);
  469. } else {
  470. fprintf(stderr, " ");
  471. }
  472. }
  473. /*
  474. * Print out the results of a single counter:
  475. * aggregated counts in system-wide mode
  476. */
  477. static void print_counter_aggr(struct perf_evsel *counter)
  478. {
  479. struct perf_stat *ps = counter->priv;
  480. double avg = avg_stats(&ps->res_stats[0]);
  481. int scaled = counter->counts->scaled;
  482. if (scaled == -1) {
  483. fprintf(stderr, "%*s%s%*s",
  484. csv_output ? 0 : 18,
  485. "<not counted>",
  486. csv_sep,
  487. csv_output ? 0 : -24,
  488. event_name(counter));
  489. if (counter->cgrp)
  490. fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
  491. fputc('\n', stderr);
  492. return;
  493. }
  494. if (nsec_counter(counter))
  495. nsec_printout(-1, counter, avg);
  496. else
  497. abs_printout(-1, counter, avg);
  498. if (csv_output) {
  499. fputc('\n', stderr);
  500. return;
  501. }
  502. print_noise(counter, avg);
  503. if (scaled) {
  504. double avg_enabled, avg_running;
  505. avg_enabled = avg_stats(&ps->res_stats[1]);
  506. avg_running = avg_stats(&ps->res_stats[2]);
  507. fprintf(stderr, " (scaled from %.2f%%)",
  508. 100 * avg_running / avg_enabled);
  509. }
  510. fprintf(stderr, "\n");
  511. }
  512. /*
  513. * Print out the results of a single counter:
  514. * does not use aggregated count in system-wide
  515. */
  516. static void print_counter(struct perf_evsel *counter)
  517. {
  518. u64 ena, run, val;
  519. int cpu;
  520. for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
  521. val = counter->counts->cpu[cpu].val;
  522. ena = counter->counts->cpu[cpu].ena;
  523. run = counter->counts->cpu[cpu].run;
  524. if (run == 0 || ena == 0) {
  525. fprintf(stderr, "CPU%*d%s%*s%s%*s",
  526. csv_output ? 0 : -4,
  527. evsel_list->cpus->map[cpu], csv_sep,
  528. csv_output ? 0 : 18,
  529. "<not counted>", csv_sep,
  530. csv_output ? 0 : -24,
  531. event_name(counter));
  532. if (counter->cgrp)
  533. fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
  534. fputc('\n', stderr);
  535. continue;
  536. }
  537. if (nsec_counter(counter))
  538. nsec_printout(cpu, counter, val);
  539. else
  540. abs_printout(cpu, counter, val);
  541. if (!csv_output) {
  542. print_noise(counter, 1.0);
  543. if (run != ena) {
  544. fprintf(stderr, " (scaled from %.2f%%)",
  545. 100.0 * run / ena);
  546. }
  547. }
  548. fputc('\n', stderr);
  549. }
  550. }
  551. static void print_stat(int argc, const char **argv)
  552. {
  553. struct perf_evsel *counter;
  554. int i;
  555. fflush(stdout);
  556. if (!csv_output) {
  557. fprintf(stderr, "\n");
  558. fprintf(stderr, " Performance counter stats for ");
  559. if(target_pid == -1 && target_tid == -1) {
  560. fprintf(stderr, "\'%s", argv[0]);
  561. for (i = 1; i < argc; i++)
  562. fprintf(stderr, " %s", argv[i]);
  563. } else if (target_pid != -1)
  564. fprintf(stderr, "process id \'%d", target_pid);
  565. else
  566. fprintf(stderr, "thread id \'%d", target_tid);
  567. fprintf(stderr, "\'");
  568. if (run_count > 1)
  569. fprintf(stderr, " (%d runs)", run_count);
  570. fprintf(stderr, ":\n\n");
  571. }
  572. if (no_aggr) {
  573. list_for_each_entry(counter, &evsel_list->entries, node)
  574. print_counter(counter);
  575. } else {
  576. list_for_each_entry(counter, &evsel_list->entries, node)
  577. print_counter_aggr(counter);
  578. }
  579. if (!csv_output) {
  580. fprintf(stderr, "\n");
  581. fprintf(stderr, " %18.9f seconds time elapsed",
  582. avg_stats(&walltime_nsecs_stats)/1e9);
  583. if (run_count > 1) {
  584. print_noise_pct(stddev_stats(&walltime_nsecs_stats),
  585. avg_stats(&walltime_nsecs_stats));
  586. }
  587. fprintf(stderr, "\n\n");
  588. }
  589. }
  590. static volatile int signr = -1;
  591. static void skip_signal(int signo)
  592. {
  593. if(child_pid == -1)
  594. done = 1;
  595. signr = signo;
  596. }
  597. static void sig_atexit(void)
  598. {
  599. if (child_pid != -1)
  600. kill(child_pid, SIGTERM);
  601. if (signr == -1)
  602. return;
  603. signal(signr, SIG_DFL);
  604. kill(getpid(), signr);
  605. }
  606. static const char * const stat_usage[] = {
  607. "perf stat [<options>] [<command>]",
  608. NULL
  609. };
  610. static int stat__set_big_num(const struct option *opt __used,
  611. const char *s __used, int unset)
  612. {
  613. big_num_opt = unset ? 0 : 1;
  614. return 0;
  615. }
  616. static const struct option options[] = {
  617. OPT_CALLBACK('e', "event", &evsel_list, "event",
  618. "event selector. use 'perf list' to list available events",
  619. parse_events),
  620. OPT_CALLBACK(0, "filter", &evsel_list, "filter",
  621. "event filter", parse_filter),
  622. OPT_BOOLEAN('i', "no-inherit", &no_inherit,
  623. "child tasks do not inherit counters"),
  624. OPT_INTEGER('p', "pid", &target_pid,
  625. "stat events on existing process id"),
  626. OPT_INTEGER('t', "tid", &target_tid,
  627. "stat events on existing thread id"),
  628. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  629. "system-wide collection from all CPUs"),
  630. OPT_BOOLEAN('c', "scale", &scale,
  631. "scale/normalize counters"),
  632. OPT_INCR('v', "verbose", &verbose,
  633. "be more verbose (show counter open errors, etc)"),
  634. OPT_INTEGER('r', "repeat", &run_count,
  635. "repeat command and print average + stddev (max: 100)"),
  636. OPT_BOOLEAN('n', "null", &null_run,
  637. "null run - dont start any counters"),
  638. OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
  639. "print large numbers with thousands\' separators",
  640. stat__set_big_num),
  641. OPT_STRING('C', "cpu", &cpu_list, "cpu",
  642. "list of cpus to monitor in system-wide"),
  643. OPT_BOOLEAN('A', "no-aggr", &no_aggr,
  644. "disable CPU count aggregation"),
  645. OPT_STRING('x', "field-separator", &csv_sep, "separator",
  646. "print counts with custom separator"),
  647. OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
  648. "monitor event in cgroup name only",
  649. parse_cgroups),
  650. OPT_END()
  651. };
  652. int cmd_stat(int argc, const char **argv, const char *prefix __used)
  653. {
  654. struct perf_evsel *pos;
  655. int status = -ENOMEM;
  656. setlocale(LC_ALL, "");
  657. evsel_list = perf_evlist__new(NULL, NULL);
  658. if (evsel_list == NULL)
  659. return -ENOMEM;
  660. argc = parse_options(argc, argv, options, stat_usage,
  661. PARSE_OPT_STOP_AT_NON_OPTION);
  662. if (csv_sep)
  663. csv_output = true;
  664. else
  665. csv_sep = DEFAULT_SEPARATOR;
  666. /*
  667. * let the spreadsheet do the pretty-printing
  668. */
  669. if (csv_output) {
  670. /* User explicitely passed -B? */
  671. if (big_num_opt == 1) {
  672. fprintf(stderr, "-B option not supported with -x\n");
  673. usage_with_options(stat_usage, options);
  674. } else /* Nope, so disable big number formatting */
  675. big_num = false;
  676. } else if (big_num_opt == 0) /* User passed --no-big-num */
  677. big_num = false;
  678. if (!argc && target_pid == -1 && target_tid == -1)
  679. usage_with_options(stat_usage, options);
  680. if (run_count <= 0)
  681. usage_with_options(stat_usage, options);
  682. /* no_aggr, cgroup are for system-wide only */
  683. if ((no_aggr || nr_cgroups) && !system_wide) {
  684. fprintf(stderr, "both cgroup and no-aggregation "
  685. "modes only available in system-wide mode\n");
  686. usage_with_options(stat_usage, options);
  687. }
  688. /* Set attrs and nr_counters if no event is selected and !null_run */
  689. if (!null_run && !evsel_list->nr_entries) {
  690. size_t c;
  691. for (c = 0; c < ARRAY_SIZE(default_attrs); ++c) {
  692. pos = perf_evsel__new(&default_attrs[c], c);
  693. if (pos == NULL)
  694. goto out;
  695. perf_evlist__add(evsel_list, pos);
  696. }
  697. }
  698. if (target_pid != -1)
  699. target_tid = target_pid;
  700. evsel_list->threads = thread_map__new(target_pid, target_tid);
  701. if (evsel_list->threads == NULL) {
  702. pr_err("Problems finding threads of monitor\n");
  703. usage_with_options(stat_usage, options);
  704. }
  705. if (system_wide)
  706. evsel_list->cpus = cpu_map__new(cpu_list);
  707. else
  708. evsel_list->cpus = cpu_map__dummy_new();
  709. if (evsel_list->cpus == NULL) {
  710. perror("failed to parse CPUs map");
  711. usage_with_options(stat_usage, options);
  712. return -1;
  713. }
  714. list_for_each_entry(pos, &evsel_list->entries, node) {
  715. if (perf_evsel__alloc_stat_priv(pos) < 0 ||
  716. perf_evsel__alloc_counts(pos, evsel_list->cpus->nr) < 0 ||
  717. perf_evsel__alloc_fd(pos, evsel_list->cpus->nr, evsel_list->threads->nr) < 0)
  718. goto out_free_fd;
  719. }
  720. /*
  721. * We dont want to block the signals - that would cause
  722. * child tasks to inherit that and Ctrl-C would not work.
  723. * What we want is for Ctrl-C to work in the exec()-ed
  724. * task, but being ignored by perf stat itself:
  725. */
  726. atexit(sig_atexit);
  727. signal(SIGINT, skip_signal);
  728. signal(SIGALRM, skip_signal);
  729. signal(SIGABRT, skip_signal);
  730. status = 0;
  731. for (run_idx = 0; run_idx < run_count; run_idx++) {
  732. if (run_count != 1 && verbose)
  733. fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
  734. status = run_perf_stat(argc, argv);
  735. }
  736. if (status != -1)
  737. print_stat(argc, argv);
  738. out_free_fd:
  739. list_for_each_entry(pos, &evsel_list->entries, node)
  740. perf_evsel__free_stat_priv(pos);
  741. perf_evlist__delete_maps(evsel_list);
  742. out:
  743. perf_evlist__delete(evsel_list);
  744. return status;
  745. }