builtin-stat.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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/evsel.h"
  41. #include "util/debug.h"
  42. #include "util/header.h"
  43. #include "util/cpumap.h"
  44. #include "util/thread.h"
  45. #include <sys/prctl.h>
  46. #include <math.h>
  47. #include <locale.h>
  48. #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
  49. #define DEFAULT_SEPARATOR " "
  50. static struct perf_event_attr default_attrs[] = {
  51. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK },
  52. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES },
  53. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS },
  54. { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS },
  55. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES },
  56. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS },
  57. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
  58. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES },
  59. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CACHE_REFERENCES },
  60. { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CACHE_MISSES },
  61. };
  62. static bool system_wide = false;
  63. static int nr_cpus = 0;
  64. static int run_idx = 0;
  65. static int run_count = 1;
  66. static bool no_inherit = false;
  67. static bool scale = true;
  68. static bool no_aggr = false;
  69. static pid_t target_pid = -1;
  70. static pid_t target_tid = -1;
  71. static pid_t *all_tids = NULL;
  72. static int thread_num = 0;
  73. static pid_t child_pid = -1;
  74. static bool null_run = false;
  75. static bool big_num = true;
  76. static int big_num_opt = -1;
  77. static const char *cpu_list;
  78. static const char *csv_sep = NULL;
  79. static bool csv_output = false;
  80. struct cpu_counts {
  81. u64 val;
  82. u64 ena;
  83. u64 run;
  84. };
  85. static volatile int done = 0;
  86. struct stats
  87. {
  88. double n, mean, M2;
  89. };
  90. struct perf_stat {
  91. struct stats res_stats[3];
  92. int scaled;
  93. struct cpu_counts cpu_counts[];
  94. };
  95. static int perf_evsel__alloc_stat_priv(struct perf_evsel *evsel, int ncpus)
  96. {
  97. size_t priv_size = (sizeof(struct perf_stat) +
  98. (ncpus * sizeof(struct cpu_counts)));
  99. evsel->priv = zalloc(priv_size);
  100. return evsel->priv == NULL ? -ENOMEM : 0;
  101. }
  102. static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
  103. {
  104. free(evsel->priv);
  105. evsel->priv = NULL;
  106. }
  107. static void update_stats(struct stats *stats, u64 val)
  108. {
  109. double delta;
  110. stats->n++;
  111. delta = val - stats->mean;
  112. stats->mean += delta / stats->n;
  113. stats->M2 += delta*(val - stats->mean);
  114. }
  115. static double avg_stats(struct stats *stats)
  116. {
  117. return stats->mean;
  118. }
  119. /*
  120. * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  121. *
  122. * (\Sum n_i^2) - ((\Sum n_i)^2)/n
  123. * s^2 = -------------------------------
  124. * n - 1
  125. *
  126. * http://en.wikipedia.org/wiki/Stddev
  127. *
  128. * The std dev of the mean is related to the std dev by:
  129. *
  130. * s
  131. * s_mean = -------
  132. * sqrt(n)
  133. *
  134. */
  135. static double stddev_stats(struct stats *stats)
  136. {
  137. double variance = stats->M2 / (stats->n - 1);
  138. double variance_mean = variance / stats->n;
  139. return sqrt(variance_mean);
  140. }
  141. struct stats runtime_nsecs_stats[MAX_NR_CPUS];
  142. struct stats runtime_cycles_stats[MAX_NR_CPUS];
  143. struct stats runtime_branches_stats[MAX_NR_CPUS];
  144. struct stats walltime_nsecs_stats;
  145. #define MATCH_EVENT(t, c, evsel) \
  146. (evsel->attr.type == PERF_TYPE_##t && \
  147. evsel->attr.config == PERF_COUNT_##c)
  148. #define ERR_PERF_OPEN \
  149. "counter %d, sys_perf_event_open() syscall returned with %d (%s). /bin/dmesg may provide additional information."
  150. static int create_perf_stat_counter(struct perf_evsel *evsel, bool *perm_err)
  151. {
  152. struct perf_event_attr *attr = &evsel->attr;
  153. int thread;
  154. int ncreated = 0;
  155. if (scale)
  156. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  157. PERF_FORMAT_TOTAL_TIME_RUNNING;
  158. if (system_wide) {
  159. int cpu;
  160. for (cpu = 0; cpu < nr_cpus; cpu++) {
  161. FD(evsel, cpu, 0) = sys_perf_event_open(attr,
  162. -1, cpumap[cpu], -1, 0);
  163. if (FD(evsel, cpu, 0) < 0) {
  164. if (errno == EPERM || errno == EACCES)
  165. *perm_err = true;
  166. error(ERR_PERF_OPEN, evsel->idx,
  167. FD(evsel, cpu, 0), strerror(errno));
  168. } else {
  169. ++ncreated;
  170. }
  171. }
  172. } else {
  173. attr->inherit = !no_inherit;
  174. if (target_pid == -1 && target_tid == -1) {
  175. attr->disabled = 1;
  176. attr->enable_on_exec = 1;
  177. }
  178. for (thread = 0; thread < thread_num; thread++) {
  179. FD(evsel, 0, thread) = sys_perf_event_open(attr,
  180. all_tids[thread], -1, -1, 0);
  181. if (FD(evsel, 0, thread) < 0) {
  182. if (errno == EPERM || errno == EACCES)
  183. *perm_err = true;
  184. error(ERR_PERF_OPEN, evsel->idx,
  185. FD(evsel, 0, thread),
  186. strerror(errno));
  187. } else {
  188. ++ncreated;
  189. }
  190. }
  191. }
  192. return ncreated;
  193. }
  194. /*
  195. * Does the counter have nsecs as a unit?
  196. */
  197. static inline int nsec_counter(struct perf_evsel *counter)
  198. {
  199. if (MATCH_EVENT(SOFTWARE, SW_CPU_CLOCK, counter) ||
  200. MATCH_EVENT(SOFTWARE, SW_TASK_CLOCK, counter))
  201. return 1;
  202. return 0;
  203. }
  204. /*
  205. * Read out the results of a single counter:
  206. * aggregate counts across CPUs in system-wide mode
  207. */
  208. static void read_counter_aggr(struct perf_evsel *counter)
  209. {
  210. struct perf_stat *ps = counter->priv;
  211. u64 count[3], single_count[3];
  212. int cpu;
  213. size_t res, nv;
  214. int scaled;
  215. int i, thread;
  216. count[0] = count[1] = count[2] = 0;
  217. nv = scale ? 3 : 1;
  218. for (cpu = 0; cpu < nr_cpus; cpu++) {
  219. for (thread = 0; thread < thread_num; thread++) {
  220. if (FD(counter, cpu, thread) < 0)
  221. continue;
  222. res = read(FD(counter, cpu, thread),
  223. single_count, nv * sizeof(u64));
  224. assert(res == nv * sizeof(u64));
  225. close(FD(counter, cpu, thread));
  226. FD(counter, cpu, thread) = -1;
  227. count[0] += single_count[0];
  228. if (scale) {
  229. count[1] += single_count[1];
  230. count[2] += single_count[2];
  231. }
  232. }
  233. }
  234. scaled = 0;
  235. if (scale) {
  236. if (count[2] == 0) {
  237. ps->scaled = -1;
  238. count[0] = 0;
  239. return;
  240. }
  241. if (count[2] < count[1]) {
  242. ps->scaled = 1;
  243. count[0] = (unsigned long long)
  244. ((double)count[0] * count[1] / count[2] + 0.5);
  245. }
  246. }
  247. for (i = 0; i < 3; i++)
  248. update_stats(&ps->res_stats[i], count[i]);
  249. if (verbose) {
  250. fprintf(stderr, "%s: %Ld %Ld %Ld\n", event_name(counter),
  251. count[0], count[1], count[2]);
  252. }
  253. /*
  254. * Save the full runtime - to allow normalization during printout:
  255. */
  256. if (MATCH_EVENT(SOFTWARE, SW_TASK_CLOCK, counter))
  257. update_stats(&runtime_nsecs_stats[0], count[0]);
  258. if (MATCH_EVENT(HARDWARE, HW_CPU_CYCLES, counter))
  259. update_stats(&runtime_cycles_stats[0], count[0]);
  260. if (MATCH_EVENT(HARDWARE, HW_BRANCH_INSTRUCTIONS, counter))
  261. update_stats(&runtime_branches_stats[0], count[0]);
  262. }
  263. /*
  264. * Read out the results of a single counter:
  265. * do not aggregate counts across CPUs in system-wide mode
  266. */
  267. static void read_counter(struct perf_evsel *counter)
  268. {
  269. struct cpu_counts *cpu_counts = counter->priv;
  270. u64 count[3];
  271. int cpu;
  272. size_t res, nv;
  273. count[0] = count[1] = count[2] = 0;
  274. nv = scale ? 3 : 1;
  275. for (cpu = 0; cpu < nr_cpus; cpu++) {
  276. if (FD(counter, cpu, 0) < 0)
  277. continue;
  278. res = read(FD(counter, cpu, 0), count, nv * sizeof(u64));
  279. assert(res == nv * sizeof(u64));
  280. close(FD(counter, cpu, 0));
  281. FD(counter, cpu, 0) = -1;
  282. if (scale) {
  283. if (count[2] == 0) {
  284. count[0] = 0;
  285. } else if (count[2] < count[1]) {
  286. count[0] = (unsigned long long)
  287. ((double)count[0] * count[1] / count[2] + 0.5);
  288. }
  289. }
  290. cpu_counts[cpu].val = count[0]; /* scaled count */
  291. cpu_counts[cpu].ena = count[1];
  292. cpu_counts[cpu].run = count[2];
  293. if (MATCH_EVENT(SOFTWARE, SW_TASK_CLOCK, counter))
  294. update_stats(&runtime_nsecs_stats[cpu], count[0]);
  295. if (MATCH_EVENT(HARDWARE, HW_CPU_CYCLES, counter))
  296. update_stats(&runtime_cycles_stats[cpu], count[0]);
  297. if (MATCH_EVENT(HARDWARE, HW_BRANCH_INSTRUCTIONS, counter))
  298. update_stats(&runtime_branches_stats[cpu], count[0]);
  299. }
  300. }
  301. static int run_perf_stat(int argc __used, const char **argv)
  302. {
  303. unsigned long long t0, t1;
  304. struct perf_evsel *counter;
  305. int status = 0;
  306. int ncreated = 0;
  307. int child_ready_pipe[2], go_pipe[2];
  308. bool perm_err = false;
  309. const bool forks = (argc > 0);
  310. char buf;
  311. if (!system_wide)
  312. nr_cpus = 1;
  313. if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
  314. perror("failed to create pipes");
  315. exit(1);
  316. }
  317. if (forks) {
  318. if ((child_pid = fork()) < 0)
  319. perror("failed to fork");
  320. if (!child_pid) {
  321. close(child_ready_pipe[0]);
  322. close(go_pipe[1]);
  323. fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
  324. /*
  325. * Do a dummy execvp to get the PLT entry resolved,
  326. * so we avoid the resolver overhead on the real
  327. * execvp call.
  328. */
  329. execvp("", (char **)argv);
  330. /*
  331. * Tell the parent we're ready to go
  332. */
  333. close(child_ready_pipe[1]);
  334. /*
  335. * Wait until the parent tells us to go.
  336. */
  337. if (read(go_pipe[0], &buf, 1) == -1)
  338. perror("unable to read pipe");
  339. execvp(argv[0], (char **)argv);
  340. perror(argv[0]);
  341. exit(-1);
  342. }
  343. if (target_tid == -1 && target_pid == -1 && !system_wide)
  344. all_tids[0] = child_pid;
  345. /*
  346. * Wait for the child to be ready to exec.
  347. */
  348. close(child_ready_pipe[1]);
  349. close(go_pipe[0]);
  350. if (read(child_ready_pipe[0], &buf, 1) == -1)
  351. perror("unable to read pipe");
  352. close(child_ready_pipe[0]);
  353. }
  354. list_for_each_entry(counter, &evsel_list, node)
  355. ncreated += create_perf_stat_counter(counter, &perm_err);
  356. if (ncreated < nr_counters) {
  357. if (perm_err)
  358. error("You may not have permission to collect %sstats.\n"
  359. "\t Consider tweaking"
  360. " /proc/sys/kernel/perf_event_paranoid or running as root.",
  361. system_wide ? "system-wide " : "");
  362. die("Not all events could be opened.\n");
  363. if (child_pid != -1)
  364. kill(child_pid, SIGTERM);
  365. return -1;
  366. }
  367. /*
  368. * Enable counters and exec the command:
  369. */
  370. t0 = rdclock();
  371. if (forks) {
  372. close(go_pipe[1]);
  373. wait(&status);
  374. } else {
  375. while(!done) sleep(1);
  376. }
  377. t1 = rdclock();
  378. update_stats(&walltime_nsecs_stats, t1 - t0);
  379. if (no_aggr) {
  380. list_for_each_entry(counter, &evsel_list, node)
  381. read_counter(counter);
  382. } else {
  383. list_for_each_entry(counter, &evsel_list, node)
  384. read_counter_aggr(counter);
  385. }
  386. return WEXITSTATUS(status);
  387. }
  388. static void print_noise(struct perf_evsel *evsel, double avg)
  389. {
  390. struct perf_stat *ps;
  391. if (run_count == 1)
  392. return;
  393. ps = evsel->priv;
  394. fprintf(stderr, " ( +- %7.3f%% )",
  395. 100 * stddev_stats(&ps->res_stats[0]) / avg);
  396. }
  397. static void nsec_printout(int cpu, struct perf_evsel *counter, double avg)
  398. {
  399. double msecs = avg / 1e6;
  400. char cpustr[16] = { '\0', };
  401. const char *fmt = csv_output ? "%s%.6f%s%s" : "%s%18.6f%s%-24s";
  402. if (no_aggr)
  403. sprintf(cpustr, "CPU%*d%s",
  404. csv_output ? 0 : -4,
  405. cpumap[cpu], csv_sep);
  406. fprintf(stderr, fmt, cpustr, msecs, csv_sep, event_name(counter));
  407. if (csv_output)
  408. return;
  409. if (MATCH_EVENT(SOFTWARE, SW_TASK_CLOCK, counter)) {
  410. fprintf(stderr, " # %10.3f CPUs ",
  411. avg / avg_stats(&walltime_nsecs_stats));
  412. }
  413. }
  414. static void abs_printout(int cpu, struct perf_evsel *counter, double avg)
  415. {
  416. double total, ratio = 0.0;
  417. char cpustr[16] = { '\0', };
  418. const char *fmt;
  419. if (csv_output)
  420. fmt = "%s%.0f%s%s";
  421. else if (big_num)
  422. fmt = "%s%'18.0f%s%-24s";
  423. else
  424. fmt = "%s%18.0f%s%-24s";
  425. if (no_aggr)
  426. sprintf(cpustr, "CPU%*d%s",
  427. csv_output ? 0 : -4,
  428. cpumap[cpu], csv_sep);
  429. else
  430. cpu = 0;
  431. fprintf(stderr, fmt, cpustr, avg, csv_sep, event_name(counter));
  432. if (csv_output)
  433. return;
  434. if (MATCH_EVENT(HARDWARE, HW_INSTRUCTIONS, counter)) {
  435. total = avg_stats(&runtime_cycles_stats[cpu]);
  436. if (total)
  437. ratio = avg / total;
  438. fprintf(stderr, " # %10.3f IPC ", ratio);
  439. } else if (MATCH_EVENT(HARDWARE, HW_BRANCH_MISSES, counter) &&
  440. runtime_branches_stats[cpu].n != 0) {
  441. total = avg_stats(&runtime_branches_stats[cpu]);
  442. if (total)
  443. ratio = avg * 100 / total;
  444. fprintf(stderr, " # %10.3f %% ", ratio);
  445. } else if (runtime_nsecs_stats[cpu].n != 0) {
  446. total = avg_stats(&runtime_nsecs_stats[cpu]);
  447. if (total)
  448. ratio = 1000.0 * avg / total;
  449. fprintf(stderr, " # %10.3f M/sec", ratio);
  450. }
  451. }
  452. /*
  453. * Print out the results of a single counter:
  454. * aggregated counts in system-wide mode
  455. */
  456. static void print_counter_aggr(struct perf_evsel *counter)
  457. {
  458. struct perf_stat *ps = counter->priv;
  459. double avg = avg_stats(&ps->res_stats[0]);
  460. int scaled = ps->scaled;
  461. if (scaled == -1) {
  462. fprintf(stderr, "%*s%s%-24s\n",
  463. csv_output ? 0 : 18,
  464. "<not counted>", csv_sep, event_name(counter));
  465. return;
  466. }
  467. if (nsec_counter(counter))
  468. nsec_printout(-1, counter, avg);
  469. else
  470. abs_printout(-1, counter, avg);
  471. if (csv_output) {
  472. fputc('\n', stderr);
  473. return;
  474. }
  475. print_noise(counter, avg);
  476. if (scaled) {
  477. double avg_enabled, avg_running;
  478. avg_enabled = avg_stats(&ps->res_stats[1]);
  479. avg_running = avg_stats(&ps->res_stats[2]);
  480. fprintf(stderr, " (scaled from %.2f%%)",
  481. 100 * avg_running / avg_enabled);
  482. }
  483. fprintf(stderr, "\n");
  484. }
  485. /*
  486. * Print out the results of a single counter:
  487. * does not use aggregated count in system-wide
  488. */
  489. static void print_counter(struct perf_evsel *counter)
  490. {
  491. struct perf_stat *ps = counter->priv;
  492. u64 ena, run, val;
  493. int cpu;
  494. for (cpu = 0; cpu < nr_cpus; cpu++) {
  495. val = ps->cpu_counts[cpu].val;
  496. ena = ps->cpu_counts[cpu].ena;
  497. run = ps->cpu_counts[cpu].run;
  498. if (run == 0 || ena == 0) {
  499. fprintf(stderr, "CPU%*d%s%*s%s%-24s",
  500. csv_output ? 0 : -4,
  501. cpumap[cpu], csv_sep,
  502. csv_output ? 0 : 18,
  503. "<not counted>", csv_sep,
  504. event_name(counter));
  505. fprintf(stderr, "\n");
  506. continue;
  507. }
  508. if (nsec_counter(counter))
  509. nsec_printout(cpu, counter, val);
  510. else
  511. abs_printout(cpu, counter, val);
  512. if (!csv_output) {
  513. print_noise(counter, 1.0);
  514. if (run != ena) {
  515. fprintf(stderr, " (scaled from %.2f%%)",
  516. 100.0 * run / ena);
  517. }
  518. }
  519. fprintf(stderr, "\n");
  520. }
  521. }
  522. static void print_stat(int argc, const char **argv)
  523. {
  524. struct perf_evsel *counter;
  525. int i;
  526. fflush(stdout);
  527. if (!csv_output) {
  528. fprintf(stderr, "\n");
  529. fprintf(stderr, " Performance counter stats for ");
  530. if(target_pid == -1 && target_tid == -1) {
  531. fprintf(stderr, "\'%s", argv[0]);
  532. for (i = 1; i < argc; i++)
  533. fprintf(stderr, " %s", argv[i]);
  534. } else if (target_pid != -1)
  535. fprintf(stderr, "process id \'%d", target_pid);
  536. else
  537. fprintf(stderr, "thread id \'%d", target_tid);
  538. fprintf(stderr, "\'");
  539. if (run_count > 1)
  540. fprintf(stderr, " (%d runs)", run_count);
  541. fprintf(stderr, ":\n\n");
  542. }
  543. if (no_aggr) {
  544. list_for_each_entry(counter, &evsel_list, node)
  545. print_counter(counter);
  546. } else {
  547. list_for_each_entry(counter, &evsel_list, node)
  548. print_counter_aggr(counter);
  549. }
  550. if (!csv_output) {
  551. fprintf(stderr, "\n");
  552. fprintf(stderr, " %18.9f seconds time elapsed",
  553. avg_stats(&walltime_nsecs_stats)/1e9);
  554. if (run_count > 1) {
  555. fprintf(stderr, " ( +- %7.3f%% )",
  556. 100*stddev_stats(&walltime_nsecs_stats) /
  557. avg_stats(&walltime_nsecs_stats));
  558. }
  559. fprintf(stderr, "\n\n");
  560. }
  561. }
  562. static volatile int signr = -1;
  563. static void skip_signal(int signo)
  564. {
  565. if(child_pid == -1)
  566. done = 1;
  567. signr = signo;
  568. }
  569. static void sig_atexit(void)
  570. {
  571. if (child_pid != -1)
  572. kill(child_pid, SIGTERM);
  573. if (signr == -1)
  574. return;
  575. signal(signr, SIG_DFL);
  576. kill(getpid(), signr);
  577. }
  578. static const char * const stat_usage[] = {
  579. "perf stat [<options>] [<command>]",
  580. NULL
  581. };
  582. static int stat__set_big_num(const struct option *opt __used,
  583. const char *s __used, int unset)
  584. {
  585. big_num_opt = unset ? 0 : 1;
  586. return 0;
  587. }
  588. static const struct option options[] = {
  589. OPT_CALLBACK('e', "event", NULL, "event",
  590. "event selector. use 'perf list' to list available events",
  591. parse_events),
  592. OPT_BOOLEAN('i', "no-inherit", &no_inherit,
  593. "child tasks do not inherit counters"),
  594. OPT_INTEGER('p', "pid", &target_pid,
  595. "stat events on existing process id"),
  596. OPT_INTEGER('t', "tid", &target_tid,
  597. "stat events on existing thread id"),
  598. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  599. "system-wide collection from all CPUs"),
  600. OPT_BOOLEAN('c', "scale", &scale,
  601. "scale/normalize counters"),
  602. OPT_INCR('v', "verbose", &verbose,
  603. "be more verbose (show counter open errors, etc)"),
  604. OPT_INTEGER('r', "repeat", &run_count,
  605. "repeat command and print average + stddev (max: 100)"),
  606. OPT_BOOLEAN('n', "null", &null_run,
  607. "null run - dont start any counters"),
  608. OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
  609. "print large numbers with thousands\' separators",
  610. stat__set_big_num),
  611. OPT_STRING('C', "cpu", &cpu_list, "cpu",
  612. "list of cpus to monitor in system-wide"),
  613. OPT_BOOLEAN('A', "no-aggr", &no_aggr,
  614. "disable CPU count aggregation"),
  615. OPT_STRING('x', "field-separator", &csv_sep, "separator",
  616. "print counts with custom separator"),
  617. OPT_END()
  618. };
  619. int cmd_stat(int argc, const char **argv, const char *prefix __used)
  620. {
  621. struct perf_evsel *pos;
  622. int status = -ENOMEM;
  623. setlocale(LC_ALL, "");
  624. argc = parse_options(argc, argv, options, stat_usage,
  625. PARSE_OPT_STOP_AT_NON_OPTION);
  626. if (csv_sep)
  627. csv_output = true;
  628. else
  629. csv_sep = DEFAULT_SEPARATOR;
  630. /*
  631. * let the spreadsheet do the pretty-printing
  632. */
  633. if (csv_output) {
  634. /* User explicitely passed -B? */
  635. if (big_num_opt == 1) {
  636. fprintf(stderr, "-B option not supported with -x\n");
  637. usage_with_options(stat_usage, options);
  638. } else /* Nope, so disable big number formatting */
  639. big_num = false;
  640. } else if (big_num_opt == 0) /* User passed --no-big-num */
  641. big_num = false;
  642. if (!argc && target_pid == -1 && target_tid == -1)
  643. usage_with_options(stat_usage, options);
  644. if (run_count <= 0)
  645. usage_with_options(stat_usage, options);
  646. /* no_aggr is for system-wide only */
  647. if (no_aggr && !system_wide)
  648. usage_with_options(stat_usage, options);
  649. /* Set attrs and nr_counters if no event is selected and !null_run */
  650. if (!null_run && !nr_counters) {
  651. size_t c;
  652. nr_counters = ARRAY_SIZE(default_attrs);
  653. for (c = 0; c < ARRAY_SIZE(default_attrs); ++c) {
  654. pos = perf_evsel__new(default_attrs[c].type,
  655. default_attrs[c].config,
  656. nr_counters);
  657. if (pos == NULL)
  658. goto out;
  659. list_add(&pos->node, &evsel_list);
  660. }
  661. }
  662. if (system_wide)
  663. nr_cpus = read_cpu_map(cpu_list);
  664. else
  665. nr_cpus = 1;
  666. if (nr_cpus < 1)
  667. usage_with_options(stat_usage, options);
  668. if (target_pid != -1) {
  669. target_tid = target_pid;
  670. thread_num = find_all_tid(target_pid, &all_tids);
  671. if (thread_num <= 0) {
  672. fprintf(stderr, "Can't find all threads of pid %d\n",
  673. target_pid);
  674. usage_with_options(stat_usage, options);
  675. }
  676. } else {
  677. all_tids=malloc(sizeof(pid_t));
  678. if (!all_tids)
  679. return -ENOMEM;
  680. all_tids[0] = target_tid;
  681. thread_num = 1;
  682. }
  683. list_for_each_entry(pos, &evsel_list, node) {
  684. if (perf_evsel__alloc_stat_priv(pos, nr_cpus) < 0 ||
  685. perf_evsel__alloc_fd(pos, nr_cpus, thread_num) < 0)
  686. goto out_free_fd;
  687. }
  688. /*
  689. * We dont want to block the signals - that would cause
  690. * child tasks to inherit that and Ctrl-C would not work.
  691. * What we want is for Ctrl-C to work in the exec()-ed
  692. * task, but being ignored by perf stat itself:
  693. */
  694. atexit(sig_atexit);
  695. signal(SIGINT, skip_signal);
  696. signal(SIGALRM, skip_signal);
  697. signal(SIGABRT, skip_signal);
  698. status = 0;
  699. for (run_idx = 0; run_idx < run_count; run_idx++) {
  700. if (run_count != 1 && verbose)
  701. fprintf(stderr, "[ perf stat: executing run #%d ... ]\n", run_idx + 1);
  702. status = run_perf_stat(argc, argv);
  703. }
  704. if (status != -1)
  705. print_stat(argc, argv);
  706. out_free_fd:
  707. list_for_each_entry(pos, &evsel_list, node) {
  708. perf_evsel__free_fd(pos);
  709. perf_evsel__free_stat_priv(pos);
  710. }
  711. out:
  712. return status;
  713. }