builtin-stat.c 13 KB

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