builtin-stat.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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 || errno == ENOENT) {
  316. if (verbose)
  317. ui__warning("%s event is not supported by the kernel.\n",
  318. event_name(counter));
  319. continue;
  320. }
  321. if (errno == EPERM || errno == EACCES) {
  322. error("You may not have permission to collect %sstats.\n"
  323. "\t Consider tweaking"
  324. " /proc/sys/kernel/perf_event_paranoid or running as root.",
  325. system_wide ? "system-wide " : "");
  326. } else {
  327. error("open_counter returned with %d (%s). "
  328. "/bin/dmesg may provide additional information.\n",
  329. errno, strerror(errno));
  330. }
  331. if (child_pid != -1)
  332. kill(child_pid, SIGTERM);
  333. die("Not all events could be opened.\n");
  334. return -1;
  335. }
  336. }
  337. if (perf_evlist__set_filters(evsel_list)) {
  338. error("failed to set filter with %d (%s)\n", errno,
  339. strerror(errno));
  340. return -1;
  341. }
  342. /*
  343. * Enable counters and exec the command:
  344. */
  345. t0 = rdclock();
  346. if (forks) {
  347. close(go_pipe[1]);
  348. wait(&status);
  349. } else {
  350. while(!done) sleep(1);
  351. }
  352. t1 = rdclock();
  353. update_stats(&walltime_nsecs_stats, t1 - t0);
  354. if (no_aggr) {
  355. list_for_each_entry(counter, &evsel_list->entries, node) {
  356. read_counter(counter);
  357. perf_evsel__close_fd(counter, evsel_list->cpus->nr, 1);
  358. }
  359. } else {
  360. list_for_each_entry(counter, &evsel_list->entries, node) {
  361. read_counter_aggr(counter);
  362. perf_evsel__close_fd(counter, evsel_list->cpus->nr,
  363. evsel_list->threads->nr);
  364. }
  365. }
  366. return WEXITSTATUS(status);
  367. }
  368. static void print_noise_pct(double total, double avg)
  369. {
  370. double pct = 0.0;
  371. if (avg)
  372. pct = 100.0*total/avg;
  373. fprintf(stderr, " ( +-%6.2f%% )", pct);
  374. }
  375. static void print_noise(struct perf_evsel *evsel, double avg)
  376. {
  377. struct perf_stat *ps;
  378. if (run_count == 1)
  379. return;
  380. ps = evsel->priv;
  381. print_noise_pct(stddev_stats(&ps->res_stats[0]), avg);
  382. }
  383. static void nsec_printout(int cpu, struct perf_evsel *evsel, double avg)
  384. {
  385. double msecs = avg / 1e6;
  386. char cpustr[16] = { '\0', };
  387. const char *fmt = csv_output ? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
  388. if (no_aggr)
  389. sprintf(cpustr, "CPU%*d%s",
  390. csv_output ? 0 : -4,
  391. evsel_list->cpus->map[cpu], csv_sep);
  392. fprintf(stderr, fmt, cpustr, msecs, csv_sep, event_name(evsel));
  393. if (evsel->cgrp)
  394. fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
  395. if (csv_output)
  396. return;
  397. if (perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK))
  398. fprintf(stderr, " # %8.3f CPUs utilized ", avg / avg_stats(&walltime_nsecs_stats));
  399. }
  400. static void print_stalled_cycles_frontend(int cpu, struct perf_evsel *evsel __used, double avg)
  401. {
  402. double total, ratio = 0.0;
  403. const char *color;
  404. total = avg_stats(&runtime_cycles_stats[cpu]);
  405. if (total)
  406. ratio = avg / total * 100.0;
  407. color = PERF_COLOR_NORMAL;
  408. if (ratio > 50.0)
  409. color = PERF_COLOR_RED;
  410. else if (ratio > 30.0)
  411. color = PERF_COLOR_MAGENTA;
  412. else if (ratio > 10.0)
  413. color = PERF_COLOR_YELLOW;
  414. fprintf(stderr, " # ");
  415. color_fprintf(stderr, color, "%6.2f%%", ratio);
  416. fprintf(stderr, " frontend cycles idle ");
  417. }
  418. static void print_stalled_cycles_backend(int cpu, struct perf_evsel *evsel __used, double avg)
  419. {
  420. double total, ratio = 0.0;
  421. const char *color;
  422. total = avg_stats(&runtime_cycles_stats[cpu]);
  423. if (total)
  424. ratio = avg / total * 100.0;
  425. color = PERF_COLOR_NORMAL;
  426. if (ratio > 75.0)
  427. color = PERF_COLOR_RED;
  428. else if (ratio > 50.0)
  429. color = PERF_COLOR_MAGENTA;
  430. else if (ratio > 20.0)
  431. color = PERF_COLOR_YELLOW;
  432. fprintf(stderr, " # ");
  433. color_fprintf(stderr, color, "%6.2f%%", ratio);
  434. fprintf(stderr, " backend cycles idle ");
  435. }
  436. static void print_branch_misses(int cpu, struct perf_evsel *evsel __used, double avg)
  437. {
  438. double total, ratio = 0.0;
  439. const char *color;
  440. total = avg_stats(&runtime_branches_stats[cpu]);
  441. if (total)
  442. ratio = avg / total * 100.0;
  443. color = PERF_COLOR_NORMAL;
  444. if (ratio > 20.0)
  445. color = PERF_COLOR_RED;
  446. else if (ratio > 10.0)
  447. color = PERF_COLOR_MAGENTA;
  448. else if (ratio > 5.0)
  449. color = PERF_COLOR_YELLOW;
  450. fprintf(stderr, " # ");
  451. color_fprintf(stderr, color, "%6.2f%%", ratio);
  452. fprintf(stderr, " of all branches ");
  453. }
  454. static void print_l1_dcache_misses(int cpu, struct perf_evsel *evsel __used, double avg)
  455. {
  456. double total, ratio = 0.0;
  457. const char *color;
  458. total = avg_stats(&runtime_l1_dcache_stats[cpu]);
  459. if (total)
  460. ratio = avg / total * 100.0;
  461. color = PERF_COLOR_NORMAL;
  462. if (ratio > 20.0)
  463. color = PERF_COLOR_RED;
  464. else if (ratio > 10.0)
  465. color = PERF_COLOR_MAGENTA;
  466. else if (ratio > 5.0)
  467. color = PERF_COLOR_YELLOW;
  468. fprintf(stderr, " # ");
  469. color_fprintf(stderr, color, "%6.2f%%", ratio);
  470. fprintf(stderr, " of all L1-dcache hits ");
  471. }
  472. static void abs_printout(int cpu, struct perf_evsel *evsel, double avg)
  473. {
  474. double total, ratio = 0.0;
  475. char cpustr[16] = { '\0', };
  476. const char *fmt;
  477. if (csv_output)
  478. fmt = "%s%.0f%s%s";
  479. else if (big_num)
  480. fmt = "%s%'18.0f%s%-24s";
  481. else
  482. fmt = "%s%18.0f%s%-24s";
  483. if (no_aggr)
  484. sprintf(cpustr, "CPU%*d%s",
  485. csv_output ? 0 : -4,
  486. evsel_list->cpus->map[cpu], csv_sep);
  487. else
  488. cpu = 0;
  489. fprintf(stderr, fmt, cpustr, avg, csv_sep, event_name(evsel));
  490. if (evsel->cgrp)
  491. fprintf(stderr, "%s%s", csv_sep, evsel->cgrp->name);
  492. if (csv_output)
  493. return;
  494. if (perf_evsel__match(evsel, HARDWARE, HW_INSTRUCTIONS)) {
  495. total = avg_stats(&runtime_cycles_stats[cpu]);
  496. if (total)
  497. ratio = avg / total;
  498. fprintf(stderr, " # %5.2f insns per cycle ", ratio);
  499. total = avg_stats(&runtime_stalled_cycles_front_stats[cpu]);
  500. total = max(total, avg_stats(&runtime_stalled_cycles_back_stats[cpu]));
  501. if (total && avg) {
  502. ratio = total / avg;
  503. fprintf(stderr, "\n # %5.2f stalled cycles per insn", ratio);
  504. }
  505. } else if (perf_evsel__match(evsel, HARDWARE, HW_BRANCH_MISSES) &&
  506. runtime_branches_stats[cpu].n != 0) {
  507. print_branch_misses(cpu, evsel, avg);
  508. } else if (
  509. evsel->attr.type == PERF_TYPE_HW_CACHE &&
  510. evsel->attr.config == ( PERF_COUNT_HW_CACHE_L1D |
  511. ((PERF_COUNT_HW_CACHE_OP_READ) << 8) |
  512. ((PERF_COUNT_HW_CACHE_RESULT_MISS) << 16)) &&
  513. runtime_l1_dcache_stats[cpu].n != 0) {
  514. print_l1_dcache_misses(cpu, evsel, avg);
  515. } else if (perf_evsel__match(evsel, HARDWARE, HW_CACHE_MISSES) &&
  516. runtime_cacherefs_stats[cpu].n != 0) {
  517. total = avg_stats(&runtime_cacherefs_stats[cpu]);
  518. if (total)
  519. ratio = avg * 100 / total;
  520. fprintf(stderr, " # %8.3f %% of all cache refs ", ratio);
  521. } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES_FRONTEND)) {
  522. print_stalled_cycles_frontend(cpu, evsel, avg);
  523. } else if (perf_evsel__match(evsel, HARDWARE, HW_STALLED_CYCLES_BACKEND)) {
  524. print_stalled_cycles_backend(cpu, evsel, avg);
  525. } else if (perf_evsel__match(evsel, HARDWARE, HW_CPU_CYCLES)) {
  526. total = avg_stats(&runtime_nsecs_stats[cpu]);
  527. if (total)
  528. ratio = 1.0 * avg / total;
  529. fprintf(stderr, " # %8.3f GHz ", ratio);
  530. } else if (runtime_nsecs_stats[cpu].n != 0) {
  531. total = avg_stats(&runtime_nsecs_stats[cpu]);
  532. if (total)
  533. ratio = 1000.0 * avg / total;
  534. fprintf(stderr, " # %8.3f M/sec ", ratio);
  535. } else {
  536. fprintf(stderr, " ");
  537. }
  538. }
  539. /*
  540. * Print out the results of a single counter:
  541. * aggregated counts in system-wide mode
  542. */
  543. static void print_counter_aggr(struct perf_evsel *counter)
  544. {
  545. struct perf_stat *ps = counter->priv;
  546. double avg = avg_stats(&ps->res_stats[0]);
  547. int scaled = counter->counts->scaled;
  548. if (scaled == -1) {
  549. fprintf(stderr, "%*s%s%*s",
  550. csv_output ? 0 : 18,
  551. "<not counted>",
  552. csv_sep,
  553. csv_output ? 0 : -24,
  554. event_name(counter));
  555. if (counter->cgrp)
  556. fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
  557. fputc('\n', stderr);
  558. return;
  559. }
  560. if (nsec_counter(counter))
  561. nsec_printout(-1, counter, avg);
  562. else
  563. abs_printout(-1, counter, avg);
  564. if (csv_output) {
  565. fputc('\n', stderr);
  566. return;
  567. }
  568. print_noise(counter, avg);
  569. if (scaled) {
  570. double avg_enabled, avg_running;
  571. avg_enabled = avg_stats(&ps->res_stats[1]);
  572. avg_running = avg_stats(&ps->res_stats[2]);
  573. fprintf(stderr, " (%.2f%%)", 100 * avg_running / avg_enabled);
  574. }
  575. fprintf(stderr, "\n");
  576. }
  577. /*
  578. * Print out the results of a single counter:
  579. * does not use aggregated count in system-wide
  580. */
  581. static void print_counter(struct perf_evsel *counter)
  582. {
  583. u64 ena, run, val;
  584. int cpu;
  585. for (cpu = 0; cpu < evsel_list->cpus->nr; cpu++) {
  586. val = counter->counts->cpu[cpu].val;
  587. ena = counter->counts->cpu[cpu].ena;
  588. run = counter->counts->cpu[cpu].run;
  589. if (run == 0 || ena == 0) {
  590. fprintf(stderr, "CPU%*d%s%*s%s%*s",
  591. csv_output ? 0 : -4,
  592. evsel_list->cpus->map[cpu], csv_sep,
  593. csv_output ? 0 : 18,
  594. "<not counted>", csv_sep,
  595. csv_output ? 0 : -24,
  596. event_name(counter));
  597. if (counter->cgrp)
  598. fprintf(stderr, "%s%s", csv_sep, counter->cgrp->name);
  599. fputc('\n', stderr);
  600. continue;
  601. }
  602. if (nsec_counter(counter))
  603. nsec_printout(cpu, counter, val);
  604. else
  605. abs_printout(cpu, counter, val);
  606. if (!csv_output) {
  607. print_noise(counter, 1.0);
  608. if (run != ena)
  609. fprintf(stderr, " (%.2f%%)", 100.0 * run / ena);
  610. }
  611. fputc('\n', stderr);
  612. }
  613. }
  614. static void print_stat(int argc, const char **argv)
  615. {
  616. struct perf_evsel *counter;
  617. int i;
  618. fflush(stdout);
  619. if (!csv_output) {
  620. fprintf(stderr, "\n");
  621. fprintf(stderr, " Performance counter stats for ");
  622. if(target_pid == -1 && target_tid == -1) {
  623. fprintf(stderr, "\'%s", argv[0]);
  624. for (i = 1; i < argc; i++)
  625. fprintf(stderr, " %s", argv[i]);
  626. } else if (target_pid != -1)
  627. fprintf(stderr, "process id \'%d", target_pid);
  628. else
  629. fprintf(stderr, "thread id \'%d", target_tid);
  630. fprintf(stderr, "\'");
  631. if (run_count > 1)
  632. fprintf(stderr, " (%d runs)", run_count);
  633. fprintf(stderr, ":\n\n");
  634. }
  635. if (no_aggr) {
  636. list_for_each_entry(counter, &evsel_list->entries, node)
  637. print_counter(counter);
  638. } else {
  639. list_for_each_entry(counter, &evsel_list->entries, node)
  640. print_counter_aggr(counter);
  641. }
  642. if (!csv_output) {
  643. fprintf(stderr, "\n");
  644. fprintf(stderr, " %18.9f seconds time elapsed",
  645. avg_stats(&walltime_nsecs_stats)/1e9);
  646. if (run_count > 1) {
  647. print_noise_pct(stddev_stats(&walltime_nsecs_stats),
  648. avg_stats(&walltime_nsecs_stats));
  649. }
  650. fprintf(stderr, "\n\n");
  651. }
  652. }
  653. static volatile int signr = -1;
  654. static void skip_signal(int signo)
  655. {
  656. if(child_pid == -1)
  657. done = 1;
  658. signr = signo;
  659. }
  660. static void sig_atexit(void)
  661. {
  662. if (child_pid != -1)
  663. kill(child_pid, SIGTERM);
  664. if (signr == -1)
  665. return;
  666. signal(signr, SIG_DFL);
  667. kill(getpid(), signr);
  668. }
  669. static const char * const stat_usage[] = {
  670. "perf stat [<options>] [<command>]",
  671. NULL
  672. };
  673. static int stat__set_big_num(const struct option *opt __used,
  674. const char *s __used, int unset)
  675. {
  676. big_num_opt = unset ? 0 : 1;
  677. return 0;
  678. }
  679. static const struct option options[] = {
  680. OPT_CALLBACK('e', "event", &evsel_list, "event",
  681. "event selector. use 'perf list' to list available events",
  682. parse_events),
  683. OPT_CALLBACK(0, "filter", &evsel_list, "filter",
  684. "event filter", parse_filter),
  685. OPT_BOOLEAN('i', "no-inherit", &no_inherit,
  686. "child tasks do not inherit counters"),
  687. OPT_INTEGER('p', "pid", &target_pid,
  688. "stat events on existing process id"),
  689. OPT_INTEGER('t', "tid", &target_tid,
  690. "stat events on existing thread id"),
  691. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  692. "system-wide collection from all CPUs"),
  693. OPT_BOOLEAN('c', "scale", &scale,
  694. "scale/normalize counters"),
  695. OPT_INCR('v', "verbose", &verbose,
  696. "be more verbose (show counter open errors, etc)"),
  697. OPT_INTEGER('r', "repeat", &run_count,
  698. "repeat command and print average + stddev (max: 100)"),
  699. OPT_BOOLEAN('n', "null", &null_run,
  700. "null run - dont start any counters"),
  701. OPT_BOOLEAN('d', "detailed", &detailed_run,
  702. "detailed run - start a lot of events"),
  703. OPT_BOOLEAN('S', "sync", &sync_run,
  704. "call sync() before starting a run"),
  705. OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
  706. "print large numbers with thousands\' separators",
  707. stat__set_big_num),
  708. OPT_STRING('C', "cpu", &cpu_list, "cpu",
  709. "list of cpus to monitor in system-wide"),
  710. OPT_BOOLEAN('A', "no-aggr", &no_aggr,
  711. "disable CPU count aggregation"),
  712. OPT_STRING('x', "field-separator", &csv_sep, "separator",
  713. "print counts with custom separator"),
  714. OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
  715. "monitor event in cgroup name only",
  716. parse_cgroups),
  717. OPT_END()
  718. };
  719. int cmd_stat(int argc, const char **argv, const char *prefix __used)
  720. {
  721. struct perf_evsel *pos;
  722. int status = -ENOMEM;
  723. setlocale(LC_ALL, "");
  724. evsel_list = perf_evlist__new(NULL, NULL);
  725. if (evsel_list == NULL)
  726. return -ENOMEM;
  727. argc = parse_options(argc, argv, options, stat_usage,
  728. PARSE_OPT_STOP_AT_NON_OPTION);
  729. if (csv_sep)
  730. csv_output = true;
  731. else
  732. csv_sep = DEFAULT_SEPARATOR;
  733. /*
  734. * let the spreadsheet do the pretty-printing
  735. */
  736. if (csv_output) {
  737. /* User explicitely passed -B? */
  738. if (big_num_opt == 1) {
  739. fprintf(stderr, "-B option not supported with -x\n");
  740. usage_with_options(stat_usage, options);
  741. } else /* Nope, so disable big number formatting */
  742. big_num = false;
  743. } else if (big_num_opt == 0) /* User passed --no-big-num */
  744. big_num = false;
  745. if (!argc && target_pid == -1 && target_tid == -1)
  746. usage_with_options(stat_usage, options);
  747. if (run_count <= 0)
  748. usage_with_options(stat_usage, options);
  749. /* no_aggr, cgroup are for system-wide only */
  750. if ((no_aggr || nr_cgroups) && !system_wide) {
  751. fprintf(stderr, "both cgroup and no-aggregation "
  752. "modes only available in system-wide mode\n");
  753. usage_with_options(stat_usage, options);
  754. }
  755. /* Set attrs and nr_counters if no event is selected and !null_run */
  756. if (detailed_run) {
  757. size_t c;
  758. for (c = 0; c < ARRAY_SIZE(detailed_attrs); ++c) {
  759. pos = perf_evsel__new(&detailed_attrs[c], c);
  760. if (pos == NULL)
  761. goto out;
  762. perf_evlist__add(evsel_list, pos);
  763. }
  764. }
  765. /* Set attrs and nr_counters if no event is selected and !null_run */
  766. if (!detailed_run && !null_run && !evsel_list->nr_entries) {
  767. size_t c;
  768. for (c = 0; c < ARRAY_SIZE(default_attrs); ++c) {
  769. pos = perf_evsel__new(&default_attrs[c], c);
  770. if (pos == NULL)
  771. goto out;
  772. perf_evlist__add(evsel_list, pos);
  773. }
  774. }
  775. if (target_pid != -1)
  776. target_tid = target_pid;
  777. evsel_list->threads = thread_map__new(target_pid, target_tid);
  778. if (evsel_list->threads == NULL) {
  779. pr_err("Problems finding threads of monitor\n");
  780. usage_with_options(stat_usage, options);
  781. }
  782. if (system_wide)
  783. evsel_list->cpus = cpu_map__new(cpu_list);
  784. else
  785. evsel_list->cpus = cpu_map__dummy_new();
  786. if (evsel_list->cpus == NULL) {
  787. perror("failed to parse CPUs map");
  788. usage_with_options(stat_usage, options);
  789. return -1;
  790. }
  791. list_for_each_entry(pos, &evsel_list->entries, node) {
  792. if (perf_evsel__alloc_stat_priv(pos) < 0 ||
  793. perf_evsel__alloc_counts(pos, evsel_list->cpus->nr) < 0 ||
  794. perf_evsel__alloc_fd(pos, evsel_list->cpus->nr, evsel_list->threads->nr) < 0)
  795. goto out_free_fd;
  796. }
  797. /*
  798. * We dont want to block the signals - that would cause
  799. * child tasks to inherit that and Ctrl-C would not work.
  800. * What we want is for Ctrl-C to work in the exec()-ed
  801. * task, but being ignored by perf stat itself:
  802. */
  803. atexit(sig_atexit);
  804. signal(SIGINT, skip_signal);
  805. signal(SIGALRM, skip_signal);
  806. signal(SIGABRT, skip_signal);
  807. status = 0;
  808. for (run_idx = 0; run_idx < run_count; run_idx++) {
  809. if (run_count != 1 && verbose)
  810. fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
  811. if (sync_run)
  812. sync();
  813. status = run_perf_stat(argc, argv);
  814. }
  815. if (status != -1)
  816. print_stat(argc, argv);
  817. out_free_fd:
  818. list_for_each_entry(pos, &evsel_list->entries, node)
  819. perf_evsel__free_stat_priv(pos);
  820. perf_evlist__delete_maps(evsel_list);
  821. out:
  822. perf_evlist__delete(evsel_list);
  823. return status;
  824. }