builtin-stat.c 26 KB

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