builtin-stat.c 12 KB

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