builtin-stat.c 25 KB

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