builtin-stat.c 13 KB

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