builtin-stat.c 13 KB

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