builtin-stat.c 13 KB

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