builtin-stat.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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/debug.h"
  41. #include "util/header.h"
  42. #include "util/cpumap.h"
  43. #include "util/thread.h"
  44. #include <sys/prctl.h>
  45. #include <math.h>
  46. #include <locale.h>
  47. static struct perf_event_attr default_attrs[] = {
  48. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
  49. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
  50. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
  51. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
  52. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
  53. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
  54. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
  55. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
  56. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CACHE_REFERENCES },
  57. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CACHE_MISSES },
  58. };
  59. static bool system_wide = false;
  60. static unsigned int nr_cpus = 0;
  61. static int run_idx = 0;
  62. static int run_count = 1;
  63. static bool no_inherit = false;
  64. static bool scale = true;
  65. static pid_t target_pid = -1;
  66. static pid_t target_tid = -1;
  67. static pid_t *all_tids = NULL;
  68. static int thread_num = 0;
  69. static pid_t child_pid = -1;
  70. static bool null_run = false;
  71. static bool big_num = false;
  72. static int *fd[MAX_NR_CPUS][MAX_COUNTERS];
  73. static int event_scaled[MAX_COUNTERS];
  74. static volatile int done = 0;
  75. struct stats
  76. {
  77. double n, mean, M2;
  78. };
  79. static void update_stats(struct stats *stats, u64 val)
  80. {
  81. double delta;
  82. stats->n++;
  83. delta = val - stats->mean;
  84. stats->mean += delta / stats->n;
  85. stats->M2 += delta*(val - stats->mean);
  86. }
  87. static double avg_stats(struct stats *stats)
  88. {
  89. return stats->mean;
  90. }
  91. /*
  92. * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  93. *
  94. * (\Sum n_i^2) - ((\Sum n_i)^2)/n
  95. * s^2 = -------------------------------
  96. * n - 1
  97. *
  98. * http://en.wikipedia.org/wiki/Stddev
  99. *
  100. * The std dev of the mean is related to the std dev by:
  101. *
  102. * s
  103. * s_mean = -------
  104. * sqrt(n)
  105. *
  106. */
  107. static double stddev_stats(struct stats *stats)
  108. {
  109. double variance = stats->M2 / (stats->n - 1);
  110. double variance_mean = variance / stats->n;
  111. return sqrt(variance_mean);
  112. }
  113. struct stats event_res_stats[MAX_COUNTERS][3];
  114. struct stats runtime_nsecs_stats;
  115. struct stats walltime_nsecs_stats;
  116. struct stats runtime_cycles_stats;
  117. struct stats runtime_branches_stats;
  118. #define MATCH_EVENT(t, c, counter) \
  119. (attrs[counter].type == PERF_TYPE_##t && \
  120. attrs[counter].config == PERF_COUNT_##c)
  121. #define ERR_PERF_OPEN \
  122. "Error: counter %d, sys_perf_event_open() syscall returned with %d (%s)\n"
  123. static int create_perf_stat_counter(int counter)
  124. {
  125. struct perf_event_attr *attr = attrs + counter;
  126. int thread;
  127. int ncreated = 0;
  128. if (scale)
  129. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  130. PERF_FORMAT_TOTAL_TIME_RUNNING;
  131. if (system_wide) {
  132. unsigned int cpu;
  133. for (cpu = 0; cpu < nr_cpus; cpu++) {
  134. fd[cpu][counter][0] = sys_perf_event_open(attr,
  135. -1, cpumap[cpu], -1, 0);
  136. if (fd[cpu][counter][0] < 0)
  137. pr_debug(ERR_PERF_OPEN, counter,
  138. fd[cpu][counter][0], strerror(errno));
  139. else
  140. ++ncreated;
  141. }
  142. } else {
  143. attr->inherit = !no_inherit;
  144. if (target_pid == -1 && target_tid == -1) {
  145. attr->disabled = 1;
  146. attr->enable_on_exec = 1;
  147. }
  148. for (thread = 0; thread < thread_num; thread++) {
  149. fd[0][counter][thread] = sys_perf_event_open(attr,
  150. all_tids[thread], -1, -1, 0);
  151. if (fd[0][counter][thread] < 0)
  152. pr_debug(ERR_PERF_OPEN, counter,
  153. fd[0][counter][thread],
  154. strerror(errno));
  155. else
  156. ++ncreated;
  157. }
  158. }
  159. return ncreated;
  160. }
  161. /*
  162. * Does the counter have nsecs as a unit?
  163. */
  164. static inline int nsec_counter(int counter)
  165. {
  166. if (MATCH_EVENT(SOFTWARE, SW_CPU_CLOCK, counter) ||
  167. MATCH_EVENT(SOFTWARE, SW_TASK_CLOCK, counter))
  168. return 1;
  169. return 0;
  170. }
  171. /*
  172. * Read out the results of a single counter:
  173. */
  174. static void read_counter(int counter)
  175. {
  176. u64 count[3], single_count[3];
  177. unsigned int cpu;
  178. size_t res, nv;
  179. int scaled;
  180. int i, thread;
  181. count[0] = count[1] = count[2] = 0;
  182. nv = scale ? 3 : 1;
  183. for (cpu = 0; cpu < nr_cpus; cpu++) {
  184. for (thread = 0; thread < thread_num; thread++) {
  185. if (fd[cpu][counter][thread] < 0)
  186. continue;
  187. res = read(fd[cpu][counter][thread],
  188. single_count, nv * sizeof(u64));
  189. assert(res == nv * sizeof(u64));
  190. close(fd[cpu][counter][thread]);
  191. fd[cpu][counter][thread] = -1;
  192. count[0] += single_count[0];
  193. if (scale) {
  194. count[1] += single_count[1];
  195. count[2] += single_count[2];
  196. }
  197. }
  198. }
  199. scaled = 0;
  200. if (scale) {
  201. if (count[2] == 0) {
  202. event_scaled[counter] = -1;
  203. count[0] = 0;
  204. return;
  205. }
  206. if (count[2] < count[1]) {
  207. event_scaled[counter] = 1;
  208. count[0] = (unsigned long long)
  209. ((double)count[0] * count[1] / count[2] + 0.5);
  210. }
  211. }
  212. for (i = 0; i < 3; i++)
  213. update_stats(&event_res_stats[counter][i], count[i]);
  214. if (verbose) {
  215. fprintf(stderr, "%s: %Ld %Ld %Ld\n", event_name(counter),
  216. count[0], count[1], count[2]);
  217. }
  218. /*
  219. * Save the full runtime - to allow normalization during printout:
  220. */
  221. if (MATCH_EVENT(SOFTWARE, SW_TASK_CLOCK, counter))
  222. update_stats(&runtime_nsecs_stats, count[0]);
  223. if (MATCH_EVENT(HARDWARE, HW_CPU_CYCLES, counter))
  224. update_stats(&runtime_cycles_stats, count[0]);
  225. if (MATCH_EVENT(HARDWARE, HW_BRANCH_INSTRUCTIONS, counter))
  226. update_stats(&runtime_branches_stats, count[0]);
  227. }
  228. static int run_perf_stat(int argc __used, const char **argv)
  229. {
  230. unsigned long long t0, t1;
  231. int status = 0;
  232. int counter, ncreated = 0;
  233. int child_ready_pipe[2], go_pipe[2];
  234. const bool forks = (argc > 0);
  235. char buf;
  236. if (!system_wide)
  237. nr_cpus = 1;
  238. if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
  239. perror("failed to create pipes");
  240. exit(1);
  241. }
  242. if (forks) {
  243. if ((child_pid = fork()) < 0)
  244. perror("failed to fork");
  245. if (!child_pid) {
  246. close(child_ready_pipe[0]);
  247. close(go_pipe[1]);
  248. fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
  249. /*
  250. * Do a dummy execvp to get the PLT entry resolved,
  251. * so we avoid the resolver overhead on the real
  252. * execvp call.
  253. */
  254. execvp("", (char **)argv);
  255. /*
  256. * Tell the parent we're ready to go
  257. */
  258. close(child_ready_pipe[1]);
  259. /*
  260. * Wait until the parent tells us to go.
  261. */
  262. if (read(go_pipe[0], &buf, 1) == -1)
  263. perror("unable to read pipe");
  264. execvp(argv[0], (char **)argv);
  265. perror(argv[0]);
  266. exit(-1);
  267. }
  268. if (target_tid == -1 && target_pid == -1 && !system_wide)
  269. all_tids[0] = child_pid;
  270. /*
  271. * Wait for the child to be ready to exec.
  272. */
  273. close(child_ready_pipe[1]);
  274. close(go_pipe[0]);
  275. if (read(child_ready_pipe[0], &buf, 1) == -1)
  276. perror("unable to read pipe");
  277. close(child_ready_pipe[0]);
  278. }
  279. for (counter = 0; counter < nr_counters; counter++)
  280. ncreated += create_perf_stat_counter(counter);
  281. if (ncreated == 0) {
  282. pr_err("No permission to collect %sstats.\n"
  283. "Consider tweaking /proc/sys/kernel/perf_event_paranoid.\n",
  284. system_wide ? "system-wide " : "");
  285. if (child_pid != -1)
  286. kill(child_pid, SIGTERM);
  287. return -1;
  288. }
  289. /*
  290. * Enable counters and exec the command:
  291. */
  292. t0 = rdclock();
  293. if (forks) {
  294. close(go_pipe[1]);
  295. wait(&status);
  296. } else {
  297. while(!done) sleep(1);
  298. }
  299. t1 = rdclock();
  300. update_stats(&walltime_nsecs_stats, t1 - t0);
  301. for (counter = 0; counter < nr_counters; counter++)
  302. read_counter(counter);
  303. return WEXITSTATUS(status);
  304. }
  305. static void print_noise(int counter, double avg)
  306. {
  307. if (run_count == 1)
  308. return;
  309. fprintf(stderr, " ( +- %7.3f%% )",
  310. 100 * stddev_stats(&event_res_stats[counter][0]) / avg);
  311. }
  312. static void nsec_printout(int counter, double avg)
  313. {
  314. double msecs = avg / 1e6;
  315. fprintf(stderr, " %18.6f %-24s", msecs, event_name(counter));
  316. if (MATCH_EVENT(SOFTWARE, SW_TASK_CLOCK, counter)) {
  317. fprintf(stderr, " # %10.3f CPUs ",
  318. avg / avg_stats(&walltime_nsecs_stats));
  319. }
  320. }
  321. static void abs_printout(int counter, double avg)
  322. {
  323. double total, ratio = 0.0;
  324. if (big_num)
  325. fprintf(stderr, " %'18.0f %-24s", avg, event_name(counter));
  326. else
  327. fprintf(stderr, " %18.0f %-24s", avg, event_name(counter));
  328. if (MATCH_EVENT(HARDWARE, HW_INSTRUCTIONS, counter)) {
  329. total = avg_stats(&runtime_cycles_stats);
  330. if (total)
  331. ratio = avg / total;
  332. fprintf(stderr, " # %10.3f IPC ", ratio);
  333. } else if (MATCH_EVENT(HARDWARE, HW_BRANCH_MISSES, counter) &&
  334. runtime_branches_stats.n != 0) {
  335. total = avg_stats(&runtime_branches_stats);
  336. if (total)
  337. ratio = avg * 100 / total;
  338. fprintf(stderr, " # %10.3f %% ", ratio);
  339. } else if (runtime_nsecs_stats.n != 0) {
  340. total = avg_stats(&runtime_nsecs_stats);
  341. if (total)
  342. ratio = 1000.0 * avg / total;
  343. fprintf(stderr, " # %10.3f M/sec", ratio);
  344. }
  345. }
  346. /*
  347. * Print out the results of a single counter:
  348. */
  349. static void print_counter(int counter)
  350. {
  351. double avg = avg_stats(&event_res_stats[counter][0]);
  352. int scaled = event_scaled[counter];
  353. if (scaled == -1) {
  354. fprintf(stderr, " %18s %-24s\n",
  355. "<not counted>", event_name(counter));
  356. return;
  357. }
  358. if (nsec_counter(counter))
  359. nsec_printout(counter, avg);
  360. else
  361. abs_printout(counter, avg);
  362. print_noise(counter, avg);
  363. if (scaled) {
  364. double avg_enabled, avg_running;
  365. avg_enabled = avg_stats(&event_res_stats[counter][1]);
  366. avg_running = avg_stats(&event_res_stats[counter][2]);
  367. fprintf(stderr, " (scaled from %.2f%%)",
  368. 100 * avg_running / avg_enabled);
  369. }
  370. fprintf(stderr, "\n");
  371. }
  372. static void print_stat(int argc, const char **argv)
  373. {
  374. int i, counter;
  375. fflush(stdout);
  376. fprintf(stderr, "\n");
  377. fprintf(stderr, " Performance counter stats for ");
  378. if(target_pid == -1 && target_tid == -1) {
  379. fprintf(stderr, "\'%s", argv[0]);
  380. for (i = 1; i < argc; i++)
  381. fprintf(stderr, " %s", argv[i]);
  382. } else if (target_pid != -1)
  383. fprintf(stderr, "process id \'%d", target_pid);
  384. else
  385. fprintf(stderr, "thread id \'%d", target_tid);
  386. fprintf(stderr, "\'");
  387. if (run_count > 1)
  388. fprintf(stderr, " (%d runs)", run_count);
  389. fprintf(stderr, ":\n\n");
  390. for (counter = 0; counter < nr_counters; counter++)
  391. print_counter(counter);
  392. fprintf(stderr, "\n");
  393. fprintf(stderr, " %18.9f seconds time elapsed",
  394. avg_stats(&walltime_nsecs_stats)/1e9);
  395. if (run_count > 1) {
  396. fprintf(stderr, " ( +- %7.3f%% )",
  397. 100*stddev_stats(&walltime_nsecs_stats) /
  398. avg_stats(&walltime_nsecs_stats));
  399. }
  400. fprintf(stderr, "\n\n");
  401. }
  402. static volatile int signr = -1;
  403. static void skip_signal(int signo)
  404. {
  405. if(child_pid == -1)
  406. done = 1;
  407. signr = signo;
  408. }
  409. static void sig_atexit(void)
  410. {
  411. if (child_pid != -1)
  412. kill(child_pid, SIGTERM);
  413. if (signr == -1)
  414. return;
  415. signal(signr, SIG_DFL);
  416. kill(getpid(), signr);
  417. }
  418. static const char * const stat_usage[] = {
  419. "perf stat [<options>] [<command>]",
  420. NULL
  421. };
  422. static const struct option options[] = {
  423. OPT_CALLBACK('e', "event", NULL, "event",
  424. "event selector. use 'perf list' to list available events",
  425. parse_events),
  426. OPT_BOOLEAN('i', "no-inherit", &no_inherit,
  427. "child tasks do not inherit counters"),
  428. OPT_INTEGER('p', "pid", &target_pid,
  429. "stat events on existing process id"),
  430. OPT_INTEGER('t', "tid", &target_tid,
  431. "stat events on existing thread id"),
  432. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  433. "system-wide collection from all CPUs"),
  434. OPT_BOOLEAN('c', "scale", &scale,
  435. "scale/normalize counters"),
  436. OPT_INCR('v', "verbose", &verbose,
  437. "be more verbose (show counter open errors, etc)"),
  438. OPT_INTEGER('r', "repeat", &run_count,
  439. "repeat command and print average + stddev (max: 100)"),
  440. OPT_BOOLEAN('n', "null", &null_run,
  441. "null run - dont start any counters"),
  442. OPT_BOOLEAN('B', "big-num", &big_num,
  443. "print large numbers with thousands\' separators"),
  444. OPT_END()
  445. };
  446. int cmd_stat(int argc, const char **argv, const char *prefix __used)
  447. {
  448. int status;
  449. int i,j;
  450. setlocale(LC_ALL, "");
  451. argc = parse_options(argc, argv, options, stat_usage,
  452. PARSE_OPT_STOP_AT_NON_OPTION);
  453. if (!argc && target_pid == -1 && target_tid == -1)
  454. usage_with_options(stat_usage, options);
  455. if (run_count <= 0)
  456. usage_with_options(stat_usage, options);
  457. /* Set attrs and nr_counters if no event is selected and !null_run */
  458. if (!null_run && !nr_counters) {
  459. memcpy(attrs, default_attrs, sizeof(default_attrs));
  460. nr_counters = ARRAY_SIZE(default_attrs);
  461. }
  462. if (system_wide)
  463. nr_cpus = read_cpu_map();
  464. else
  465. nr_cpus = 1;
  466. if (target_pid != -1) {
  467. target_tid = target_pid;
  468. thread_num = find_all_tid(target_pid, &all_tids);
  469. if (thread_num <= 0) {
  470. fprintf(stderr, "Can't find all threads of pid %d\n",
  471. target_pid);
  472. usage_with_options(stat_usage, options);
  473. }
  474. } else {
  475. all_tids=malloc(sizeof(pid_t));
  476. if (!all_tids)
  477. return -ENOMEM;
  478. all_tids[0] = target_tid;
  479. thread_num = 1;
  480. }
  481. for (i = 0; i < MAX_NR_CPUS; i++) {
  482. for (j = 0; j < MAX_COUNTERS; j++) {
  483. fd[i][j] = malloc(sizeof(int)*thread_num);
  484. if (!fd[i][j])
  485. return -ENOMEM;
  486. }
  487. }
  488. /*
  489. * We dont want to block the signals - that would cause
  490. * child tasks to inherit that and Ctrl-C would not work.
  491. * What we want is for Ctrl-C to work in the exec()-ed
  492. * task, but being ignored by perf stat itself:
  493. */
  494. atexit(sig_atexit);
  495. signal(SIGINT, skip_signal);
  496. signal(SIGALRM, skip_signal);
  497. signal(SIGABRT, skip_signal);
  498. status = 0;
  499. for (run_idx = 0; run_idx < run_count; run_idx++) {
  500. if (run_count != 1 && verbose)
  501. fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
  502. status = run_perf_stat(argc, argv);
  503. }
  504. if (status != -1)
  505. print_stat(argc, argv);
  506. return status;
  507. }