builtin-stat.c 12 KB

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