builtin-stat.c 15 KB

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