perfstat.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. * perfstat: /usr/bin/time -alike performance counter statistics utility
  3. *
  4. * It summarizes the counter events of all tasks (and child tasks),
  5. * covering all CPUs that the command (or workload) executes on.
  6. * It only counts the per-task events of the workload started,
  7. * independent of how many other tasks run on those CPUs.
  8. *
  9. * Build with: cc -O2 -g -lrt -Wall -W -o perfstat perfstat.c
  10. *
  11. * Sample output:
  12. *
  13. $ ./perfstat -e 1 -e 3 -e 5 ls -lR /usr/include/ >/dev/null
  14. Performance counter stats for 'ls':
  15. 163516953 instructions
  16. 2295 cache-misses
  17. 2855182 branch-misses
  18. *
  19. * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
  20. *
  21. * Released under the GPLv2 (not later).
  22. *
  23. * Percpu counter support by: Yanmin Zhang <yanmin_zhang@linux.intel.com>
  24. * Symbolic event options by: Wu Fengguang <fengguang.wu@intel.com>
  25. */
  26. #define _GNU_SOURCE
  27. #include <assert.h>
  28. #include <getopt.h>
  29. #include <stdint.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <unistd.h>
  33. #include <ctype.h>
  34. #include <errno.h>
  35. #include <fcntl.h>
  36. #include <stdio.h>
  37. #include <time.h>
  38. #include <sys/syscall.h>
  39. #include <sys/ioctl.h>
  40. #include <sys/prctl.h>
  41. #include <sys/types.h>
  42. #include <sys/stat.h>
  43. #include <sys/time.h>
  44. #include <sys/wait.h>
  45. #include <sys/uio.h>
  46. #include <linux/unistd.h>
  47. #ifdef __x86_64__
  48. # define __NR_perf_counter_open 295
  49. #endif
  50. #ifdef __i386__
  51. # define __NR_perf_counter_open 333
  52. #endif
  53. #ifdef __powerpc__
  54. #define __NR_perf_counter_open 319
  55. #endif
  56. /*
  57. * Pick up some kernel type conventions:
  58. */
  59. #define __user
  60. #define asmlinkage
  61. typedef unsigned int __u32;
  62. typedef unsigned long long __u64;
  63. typedef long long __s64;
  64. #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
  65. /*
  66. * User-space ABI bits:
  67. */
  68. /*
  69. * Generalized performance counter event types, used by the hw_event.type
  70. * parameter of the sys_perf_counter_open() syscall:
  71. */
  72. enum hw_event_types {
  73. /*
  74. * Common hardware events, generalized by the kernel:
  75. */
  76. PERF_COUNT_CPU_CYCLES = 0,
  77. PERF_COUNT_INSTRUCTIONS = 1,
  78. PERF_COUNT_CACHE_REFERENCES = 2,
  79. PERF_COUNT_CACHE_MISSES = 3,
  80. PERF_COUNT_BRANCH_INSTRUCTIONS = 4,
  81. PERF_COUNT_BRANCH_MISSES = 5,
  82. PERF_COUNT_BUS_CYCLES = 6,
  83. PERF_HW_EVENTS_MAX = 7,
  84. /*
  85. * Special "software" counters provided by the kernel, even if
  86. * the hardware does not support performance counters. These
  87. * counters measure various physical and sw events of the
  88. * kernel (and allow the profiling of them as well):
  89. */
  90. PERF_COUNT_CPU_CLOCK = -1,
  91. PERF_COUNT_TASK_CLOCK = -2,
  92. PERF_COUNT_PAGE_FAULTS = -3,
  93. PERF_COUNT_CONTEXT_SWITCHES = -4,
  94. PERF_COUNT_CPU_MIGRATIONS = -5,
  95. PERF_SW_EVENTS_MIN = -6,
  96. };
  97. /*
  98. * IRQ-notification data record type:
  99. */
  100. enum perf_counter_record_type {
  101. PERF_RECORD_SIMPLE = 0,
  102. PERF_RECORD_IRQ = 1,
  103. PERF_RECORD_GROUP = 2,
  104. };
  105. /*
  106. * Hardware event to monitor via a performance monitoring counter:
  107. */
  108. struct perf_counter_hw_event {
  109. __s64 type;
  110. __u64 irq_period;
  111. __u64 record_type;
  112. __u64 read_format;
  113. __u64 disabled : 1, /* off by default */
  114. nmi : 1, /* NMI sampling */
  115. raw : 1, /* raw event type */
  116. inherit : 1, /* children inherit it */
  117. pinned : 1, /* must always be on PMU */
  118. exclusive : 1, /* only group on PMU */
  119. exclude_user : 1, /* don't count user */
  120. exclude_kernel : 1, /* ditto kernel */
  121. exclude_hv : 1, /* ditto hypervisor */
  122. exclude_idle : 1, /* don't count when idle */
  123. __reserved_1 : 54;
  124. __u32 extra_config_len;
  125. __u32 __reserved_4;
  126. __u64 __reserved_2;
  127. __u64 __reserved_3;
  128. };
  129. /*
  130. * Ioctls that can be done on a perf counter fd:
  131. */
  132. #define PERF_COUNTER_IOC_ENABLE _IO('$', 0)
  133. #define PERF_COUNTER_IOC_DISABLE _IO('$', 1)
  134. asmlinkage int sys_perf_counter_open(
  135. struct perf_counter_hw_event *hw_event_uptr __user,
  136. pid_t pid,
  137. int cpu,
  138. int group_fd,
  139. unsigned long flags)
  140. {
  141. int ret;
  142. ret = syscall(
  143. __NR_perf_counter_open, hw_event_uptr, pid, cpu, group_fd, flags);
  144. #if defined(__x86_64__) || defined(__i386__)
  145. if (ret < 0 && ret > -4096) {
  146. errno = -ret;
  147. ret = -1;
  148. }
  149. #endif
  150. return ret;
  151. }
  152. static char *hw_event_names [] = {
  153. "CPU cycles",
  154. "instructions",
  155. "cache references",
  156. "cache misses",
  157. "branches",
  158. "branch misses",
  159. "bus cycles",
  160. };
  161. static char *sw_event_names [] = {
  162. "cpu clock ticks",
  163. "task clock ticks",
  164. "pagefaults",
  165. "context switches",
  166. "CPU migrations",
  167. };
  168. struct event_symbol {
  169. int event;
  170. char *symbol;
  171. };
  172. static struct event_symbol event_symbols [] = {
  173. {PERF_COUNT_CPU_CYCLES, "cpu-cycles", },
  174. {PERF_COUNT_CPU_CYCLES, "cycles", },
  175. {PERF_COUNT_INSTRUCTIONS, "instructions", },
  176. {PERF_COUNT_CACHE_REFERENCES, "cache-references", },
  177. {PERF_COUNT_CACHE_MISSES, "cache-misses", },
  178. {PERF_COUNT_BRANCH_INSTRUCTIONS, "branch-instructions", },
  179. {PERF_COUNT_BRANCH_INSTRUCTIONS, "branches", },
  180. {PERF_COUNT_BRANCH_MISSES, "branch-misses", },
  181. {PERF_COUNT_BUS_CYCLES, "bus-cycles", },
  182. {PERF_COUNT_CPU_CLOCK, "cpu-ticks", },
  183. {PERF_COUNT_CPU_CLOCK, "ticks", },
  184. {PERF_COUNT_TASK_CLOCK, "task-ticks", },
  185. {PERF_COUNT_PAGE_FAULTS, "page-faults", },
  186. {PERF_COUNT_PAGE_FAULTS, "faults", },
  187. {PERF_COUNT_CONTEXT_SWITCHES, "context-switches", },
  188. {PERF_COUNT_CONTEXT_SWITCHES, "cs", },
  189. {PERF_COUNT_CPU_MIGRATIONS, "cpu-migrations", },
  190. {PERF_COUNT_CPU_MIGRATIONS, "migrations", },
  191. };
  192. #define MAX_COUNTERS 64
  193. #define MAX_NR_CPUS 256
  194. static int nr_counters = 0;
  195. static int nr_cpus = 0;
  196. static int event_id[MAX_COUNTERS] =
  197. { -2, -5, -4, -3, 0, 1, 2, 3};
  198. static int event_raw[MAX_COUNTERS];
  199. static int system_wide = 0;
  200. static void display_help(void)
  201. {
  202. unsigned int i;
  203. int e;
  204. printf(
  205. "Usage: perfstat [<events...>] <cmd...>\n\n"
  206. "PerfStat Options (up to %d event types can be specified):\n\n",
  207. MAX_COUNTERS);
  208. printf(
  209. " -e EVENT --event=EVENT # symbolic-name abbreviations");
  210. for (i = 0, e = PERF_HW_EVENTS_MAX; i < ARRAY_SIZE(event_symbols); i++) {
  211. if (e != event_symbols[i].event) {
  212. e = event_symbols[i].event;
  213. printf(
  214. "\n %2d: %-20s", e, event_symbols[i].symbol);
  215. } else
  216. printf(" %s", event_symbols[i].symbol);
  217. }
  218. printf("\n"
  219. " rNNN: raw event type\n\n"
  220. " -s # system-wide collection\n\n"
  221. " -c <cmd..> --command=<cmd..> # command+arguments to be timed.\n"
  222. "\n");
  223. exit(0);
  224. }
  225. static int type_valid(int type)
  226. {
  227. if (type >= PERF_HW_EVENTS_MAX)
  228. return 0;
  229. if (type <= PERF_SW_EVENTS_MIN)
  230. return 0;
  231. return 1;
  232. }
  233. static char *event_name(int ctr)
  234. {
  235. int type = event_id[ctr];
  236. static char buf[32];
  237. if (event_raw[ctr]) {
  238. sprintf(buf, "raw 0x%x", type);
  239. return buf;
  240. }
  241. if (!type_valid(type))
  242. return "unknown";
  243. if (type >= 0)
  244. return hw_event_names[type];
  245. return sw_event_names[-type-1];
  246. }
  247. /*
  248. * Each event can have multiple symbolic names.
  249. * Symbolic names are (almost) exactly matched.
  250. */
  251. static int match_event_symbols(char *str)
  252. {
  253. unsigned int i;
  254. if (isdigit(str[0]) || str[0] == '-')
  255. return atoi(str);
  256. for (i = 0; i < ARRAY_SIZE(event_symbols); i++) {
  257. if (!strncmp(str, event_symbols[i].symbol,
  258. strlen(event_symbols[i].symbol)))
  259. return event_symbols[i].event;
  260. }
  261. return PERF_HW_EVENTS_MAX;
  262. }
  263. static void parse_events(char *str)
  264. {
  265. int type, raw;
  266. again:
  267. nr_counters++;
  268. if (nr_counters == MAX_COUNTERS)
  269. display_help();
  270. raw = 0;
  271. if (*str == 'r') {
  272. raw = 1;
  273. ++str;
  274. type = strtol(str, NULL, 16);
  275. } else {
  276. type = match_event_symbols(str);
  277. if (!type_valid(type))
  278. display_help();
  279. }
  280. event_id[nr_counters] = type;
  281. event_raw[nr_counters] = raw;
  282. str = strstr(str, ",");
  283. if (str) {
  284. str++;
  285. goto again;
  286. }
  287. }
  288. static void process_options(int argc, char *argv[])
  289. {
  290. for (;;) {
  291. int option_index = 0;
  292. /** Options for getopt */
  293. static struct option long_options[] = {
  294. {"event", required_argument, NULL, 'e'},
  295. {"help", no_argument, NULL, 'h'},
  296. {"command", no_argument, NULL, 'c'},
  297. {NULL, 0, NULL, 0 }
  298. };
  299. int c = getopt_long(argc, argv, "+:e:c:s",
  300. long_options, &option_index);
  301. if (c == -1)
  302. break;
  303. switch (c) {
  304. case 'c':
  305. break;
  306. case 's':
  307. system_wide = 1;
  308. break;
  309. case 'e':
  310. parse_events(optarg);
  311. break;
  312. default:
  313. break;
  314. }
  315. }
  316. if (optind == argc)
  317. goto err;
  318. if (!nr_counters)
  319. nr_counters = 8;
  320. else
  321. nr_counters++;
  322. return;
  323. err:
  324. display_help();
  325. }
  326. char fault_here[1000000];
  327. #define PR_TASK_PERF_COUNTERS_DISABLE 31
  328. #define PR_TASK_PERF_COUNTERS_ENABLE 32
  329. static int fd[MAX_NR_CPUS][MAX_COUNTERS];
  330. static void create_counter(int counter)
  331. {
  332. struct perf_counter_hw_event hw_event;
  333. memset(&hw_event, 0, sizeof(hw_event));
  334. hw_event.type = event_id[counter];
  335. hw_event.raw = event_raw[counter];
  336. hw_event.record_type = PERF_RECORD_SIMPLE;
  337. hw_event.nmi = 0;
  338. if (system_wide) {
  339. int cpu;
  340. for (cpu = 0; cpu < nr_cpus; cpu ++) {
  341. fd[cpu][counter] = sys_perf_counter_open(&hw_event, -1, cpu, -1, 0);
  342. if (fd[cpu][counter] < 0) {
  343. printf("perfstat error: syscall returned with %d (%s)\n",
  344. fd[cpu][counter], strerror(errno));
  345. exit(-1);
  346. }
  347. }
  348. } else {
  349. hw_event.inherit = 1;
  350. hw_event.disabled = 1;
  351. fd[0][counter] = sys_perf_counter_open(&hw_event, 0, -1, -1, 0);
  352. if (fd[0][counter] < 0) {
  353. printf("perfstat error: syscall returned with %d (%s)\n",
  354. fd[0][counter], strerror(errno));
  355. exit(-1);
  356. }
  357. }
  358. }
  359. #define rdclock() \
  360. ({ \
  361. struct timespec ts; \
  362. \
  363. clock_gettime(CLOCK_MONOTONIC, &ts); \
  364. ts.tv_sec * 1000000000ULL + ts.tv_nsec; \
  365. })
  366. int main(int argc, char *argv[])
  367. {
  368. unsigned long long t0, t1;
  369. int counter;
  370. ssize_t res;
  371. int status;
  372. int pid;
  373. process_options(argc, argv);
  374. if (system_wide) {
  375. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  376. assert(nr_cpus <= MAX_NR_CPUS);
  377. assert(nr_cpus >= 0);
  378. } else
  379. nr_cpus = 1;
  380. for (counter = 0; counter < nr_counters; counter++)
  381. create_counter(counter);
  382. argc -= optind;
  383. argv += optind;
  384. /*
  385. * Enable counters and exec the command:
  386. */
  387. t0 = rdclock();
  388. prctl(PR_TASK_PERF_COUNTERS_ENABLE);
  389. if ((pid = fork()) < 0)
  390. perror("failed to fork");
  391. if (!pid) {
  392. if (execvp(argv[0], argv)) {
  393. perror(argv[0]);
  394. exit(-1);
  395. }
  396. }
  397. while (wait(&status) >= 0)
  398. ;
  399. prctl(PR_TASK_PERF_COUNTERS_DISABLE);
  400. t1 = rdclock();
  401. fflush(stdout);
  402. fprintf(stderr, "\n");
  403. fprintf(stderr, " Performance counter stats for \'%s\':\n",
  404. argv[0]);
  405. fprintf(stderr, "\n");
  406. for (counter = 0; counter < nr_counters; counter++) {
  407. int cpu;
  408. __u64 count, single_count;
  409. count = 0;
  410. for (cpu = 0; cpu < nr_cpus; cpu ++) {
  411. res = read(fd[cpu][counter],
  412. (char *) &single_count, sizeof(single_count));
  413. assert(res == sizeof(single_count));
  414. count += single_count;
  415. }
  416. if (!event_raw[counter] &&
  417. (event_id[counter] == PERF_COUNT_CPU_CLOCK ||
  418. event_id[counter] == PERF_COUNT_TASK_CLOCK)) {
  419. double msecs = (double)count / 1000000;
  420. fprintf(stderr, " %14.6f %-20s (msecs)\n",
  421. msecs, event_name(counter));
  422. } else {
  423. fprintf(stderr, " %14Ld %-20s (events)\n",
  424. count, event_name(counter));
  425. }
  426. if (!counter)
  427. fprintf(stderr, "\n");
  428. }
  429. fprintf(stderr, "\n");
  430. fprintf(stderr, " Wall-clock time elapsed: %12.6f msecs\n",
  431. (double)(t1-t0)/1e6);
  432. fprintf(stderr, "\n");
  433. return 0;
  434. }