builtin-stat.c 20 KB

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