builtin-stat.c 25 KB

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