time.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * 'time' utility to display resource usage of processes.
  4. * Copyright (C) 1990, 91, 92, 93, 96 Free Software Foundation, Inc.
  5. *
  6. * Licensed under GPLv2, see file LICENSE in this source tree.
  7. */
  8. /* Originally written by David Keppel <pardo@cs.washington.edu>.
  9. * Heavily modified by David MacKenzie <djm@gnu.ai.mit.edu>.
  10. * Heavily modified for busybox by Erik Andersen <andersen@codepoet.org>
  11. */
  12. //config:config TIME
  13. //config: bool "time (8.1 kb)"
  14. //config: default y
  15. //config: help
  16. //config: The time command runs the specified program with the given arguments.
  17. //config: When the command finishes, time writes a message to standard output
  18. //config: giving timing statistics about this program run.
  19. //applet:IF_TIME(APPLET(time, BB_DIR_USR_BIN, BB_SUID_DROP))
  20. //kbuild:lib-$(CONFIG_TIME) += time.o
  21. //usage:#define time_trivial_usage
  22. //usage: "[-vpa] [-o FILE] PROG ARGS"
  23. //usage:#define time_full_usage "\n\n"
  24. //usage: "Run PROG, display resource usage when it exits\n"
  25. //usage: "\n -v Verbose"
  26. //usage: "\n -p POSIX output format"
  27. //usage: "\n -f FMT Custom format"
  28. //usage: "\n -o FILE Write result to FILE"
  29. //usage: "\n -a Append (else overwrite)"
  30. #include "libbb.h"
  31. #ifndef HAVE_WAIT3
  32. static pid_t wait3(int *status, int options, struct rusage *rusage)
  33. {
  34. return wait4(-1, status, options, rusage);
  35. }
  36. #endif
  37. /* Information on the resources used by a child process. */
  38. typedef struct {
  39. int waitstatus;
  40. struct rusage ru;
  41. unsigned elapsed_ms; /* Wallclock time of process. */
  42. } resource_t;
  43. /* msec = milliseconds = 1/1,000 (1*10e-3) second.
  44. usec = microseconds = 1/1,000,000 (1*10e-6) second. */
  45. #define UL unsigned long
  46. static const char default_format[] ALIGN1 = "real\t%E\nuser\t%u\nsys\t%T";
  47. /* The output format for the -p option .*/
  48. static const char posix_format[] ALIGN1 = "real %e\nuser %U\nsys %S";
  49. /* Format string for printing all statistics verbosely.
  50. Keep this output to 24 lines so users on terminals can see it all.*/
  51. static const char long_format[] ALIGN1 =
  52. "\tCommand being timed: \"%C\"\n"
  53. "\tUser time (seconds): %U\n"
  54. "\tSystem time (seconds): %S\n"
  55. "\tPercent of CPU this job got: %P\n"
  56. "\tElapsed (wall clock) time (h:mm:ss or m:ss): %E\n"
  57. "\tAverage shared text size (kbytes): %X\n"
  58. "\tAverage unshared data size (kbytes): %D\n"
  59. "\tAverage stack size (kbytes): %p\n"
  60. "\tAverage total size (kbytes): %K\n"
  61. "\tMaximum resident set size (kbytes): %M\n"
  62. "\tAverage resident set size (kbytes): %t\n"
  63. "\tMajor (requiring I/O) page faults: %F\n"
  64. "\tMinor (reclaiming a frame) page faults: %R\n"
  65. "\tVoluntary context switches: %w\n"
  66. "\tInvoluntary context switches: %c\n"
  67. "\tSwaps: %W\n"
  68. "\tFile system inputs: %I\n"
  69. "\tFile system outputs: %O\n"
  70. "\tSocket messages sent: %s\n"
  71. "\tSocket messages received: %r\n"
  72. "\tSignals delivered: %k\n"
  73. "\tPage size (bytes): %Z\n"
  74. "\tExit status: %x";
  75. /* Wait for and fill in data on child process PID.
  76. Return 0 on error, 1 if ok. */
  77. /* pid_t is short on BSDI, so don't try to promote it. */
  78. static void resuse_end(pid_t pid, resource_t *resp)
  79. {
  80. pid_t caught;
  81. /* Ignore signals, but don't ignore the children. When wait3
  82. * returns the child process, set the time the command finished. */
  83. while ((caught = wait3(&resp->waitstatus, 0, &resp->ru)) != pid) {
  84. if (caught == -1 && errno != EINTR) {
  85. bb_simple_perror_msg("wait");
  86. return;
  87. }
  88. }
  89. resp->elapsed_ms = monotonic_ms() - resp->elapsed_ms;
  90. }
  91. static void printargv(char *const *argv)
  92. {
  93. const char *fmt = " %s" + 1;
  94. do {
  95. printf(fmt, *argv);
  96. fmt = " %s";
  97. } while (*++argv);
  98. }
  99. #ifdef UNUSED
  100. /* Return the number of kilobytes corresponding to a number of pages PAGES.
  101. (Actually, we use it to convert pages*ticks into kilobytes*ticks.)
  102. Try to do arithmetic so that the risk of overflow errors is minimized.
  103. This is funky since the pagesize could be less than 1K.
  104. Note: Some machines express getrusage statistics in terms of K,
  105. others in terms of pages. */
  106. #ifdef BB_ARCH_FIXED_PAGESIZE
  107. # define pagesize BB_ARCH_FIXED_PAGESIZE
  108. # define ptok(pagesize, pages) ptok(pages)
  109. #endif
  110. static unsigned long ptok(const unsigned pagesize, const unsigned long pages)
  111. {
  112. unsigned long tmp;
  113. /* Conversion. */
  114. if (pages > (LONG_MAX / pagesize)) { /* Could overflow. */
  115. tmp = pages / 1024; /* Smaller first, */
  116. return tmp * pagesize; /* then larger. */
  117. }
  118. /* Could underflow. */
  119. tmp = pages * pagesize; /* Larger first, */
  120. return tmp / 1024; /* then smaller. */
  121. }
  122. #undef pagesize
  123. #endif /* UNUSED */
  124. /* summarize: Report on the system use of a command.
  125. Print the FMT argument except that '%' sequences
  126. have special meaning, and '\n' and '\t' are translated into
  127. newline and tab, respectively, and '\\' is translated into '\'.
  128. The character following a '%' can be:
  129. (* means the tcsh time builtin also recognizes it)
  130. % == a literal '%'
  131. C == command name and arguments
  132. * D == average unshared data size in K (ru_idrss+ru_isrss)
  133. * E == elapsed real (wall clock) time in [hour:]min:sec
  134. * F == major page faults (required physical I/O) (ru_majflt)
  135. * I == file system inputs (ru_inblock)
  136. * K == average total mem usage (ru_idrss+ru_isrss+ru_ixrss)
  137. * M == maximum resident set size in K (ru_maxrss)
  138. * O == file system outputs (ru_oublock)
  139. * P == percent of CPU this job got (total cpu time / elapsed time)
  140. * R == minor page faults (reclaims; no physical I/O involved) (ru_minflt)
  141. * S == system (kernel) time (seconds) (ru_stime)
  142. * T == system time in [hour:]min:sec
  143. * U == user time (seconds) (ru_utime)
  144. * u == user time in [hour:]min:sec
  145. * W == times swapped out (ru_nswap)
  146. * X == average amount of shared text in K (ru_ixrss)
  147. Z == page size
  148. * c == involuntary context switches (ru_nivcsw)
  149. e == elapsed real time in seconds
  150. * k == signals delivered (ru_nsignals)
  151. p == average unshared stack size in K (ru_isrss)
  152. * r == socket messages received (ru_msgrcv)
  153. * s == socket messages sent (ru_msgsnd)
  154. t == average resident set size in K (ru_idrss)
  155. * w == voluntary context switches (ru_nvcsw)
  156. x == exit status of command
  157. Various memory usages are found by converting from page-seconds
  158. to kbytes by multiplying by the page size, dividing by 1024,
  159. and dividing by elapsed real time.
  160. FMT is the format string, interpreted as described above.
  161. COMMAND is the command and args that are being summarized.
  162. RESP is resource information on the command. */
  163. #ifndef TICKS_PER_SEC
  164. #define TICKS_PER_SEC 100
  165. #endif
  166. static void summarize(const char *fmt, char **command, resource_t *resp)
  167. {
  168. unsigned vv_ms; /* Elapsed virtual (CPU) milliseconds */
  169. unsigned cpu_ticks; /* Same, in "CPU ticks" */
  170. unsigned pagesize = bb_getpagesize();
  171. /* Impossible: we do not use WUNTRACED flag in wait()...
  172. if (WIFSTOPPED(resp->waitstatus))
  173. printf("Command stopped by signal %u\n",
  174. WSTOPSIG(resp->waitstatus));
  175. else */
  176. if (WIFSIGNALED(resp->waitstatus))
  177. printf("Command terminated by signal %u\n",
  178. WTERMSIG(resp->waitstatus));
  179. else if (WIFEXITED(resp->waitstatus) && WEXITSTATUS(resp->waitstatus))
  180. printf("Command exited with non-zero status %u\n",
  181. WEXITSTATUS(resp->waitstatus));
  182. vv_ms = (resp->ru.ru_utime.tv_sec + resp->ru.ru_stime.tv_sec) * 1000
  183. + (resp->ru.ru_utime.tv_usec + resp->ru.ru_stime.tv_usec) / 1000;
  184. #if (1000 / TICKS_PER_SEC) * TICKS_PER_SEC == 1000
  185. /* 1000 is exactly divisible by TICKS_PER_SEC (typical) */
  186. cpu_ticks = vv_ms / (1000 / TICKS_PER_SEC);
  187. #else
  188. cpu_ticks = vv_ms * (unsigned long long)TICKS_PER_SEC / 1000;
  189. #endif
  190. if (!cpu_ticks) cpu_ticks = 1; /* we divide by it, must be nonzero */
  191. while (*fmt) {
  192. /* Handle leading literal part */
  193. int n = strcspn(fmt, "%\\");
  194. if (n) {
  195. printf("%.*s", n, fmt);
  196. fmt += n;
  197. continue;
  198. }
  199. switch (*fmt) {
  200. case '%':
  201. switch (*++fmt) {
  202. default:
  203. /* Unknown %<char> is printed as "?<char>" */
  204. bb_putchar('?');
  205. if (!*fmt) {
  206. /* Trailing -f '...%' prints "...?" but NOT newline */
  207. goto ret;
  208. }
  209. /*FALLTHROUGH*/
  210. case '%':
  211. bb_putchar(*fmt);
  212. break;
  213. case 'C': /* The command that got timed. */
  214. printargv(command);
  215. break;
  216. case 'D': /* Average unshared data size. */
  217. /* (linux kernel sets ru_idrss/isrss/ixrss to 0,
  218. * docs say the value is in kbytes, so ptok() is wrong) */
  219. printf("%lu",
  220. (/*ptok(pagesize,*/ (UL) resp->ru.ru_idrss +
  221. (UL) resp->ru.ru_isrss
  222. ) / cpu_ticks
  223. );
  224. break;
  225. case 'E': { /* Elapsed real (wall clock) time. */
  226. unsigned seconds = resp->elapsed_ms / 1000;
  227. if (seconds >= 3600) /* One hour -> h:m:s. */
  228. printf("%uh %um %02us",
  229. seconds / 3600,
  230. (seconds % 3600) / 60,
  231. seconds % 60);
  232. else
  233. printf("%um %u.%02us", /* -> m:s. */
  234. seconds / 60,
  235. seconds % 60,
  236. (unsigned)(resp->elapsed_ms / 10) % 100);
  237. break;
  238. }
  239. case 'F': /* Major page faults. */
  240. printf("%lu", resp->ru.ru_majflt);
  241. break;
  242. case 'I': /* Inputs. */
  243. printf("%lu", resp->ru.ru_inblock);
  244. break;
  245. case 'K': /* Average mem usage == data+stack+text. */
  246. /* (linux kernel sets ru_idrss/isrss/ixrss to 0,
  247. * docs say the value is in kbytes, so ptok() is wrong) */
  248. printf("%lu",
  249. (/*ptok(pagesize,*/ (UL) resp->ru.ru_idrss +
  250. (UL) resp->ru.ru_isrss +
  251. (UL) resp->ru.ru_ixrss
  252. ) / cpu_ticks
  253. );
  254. break;
  255. case 'M': /* Maximum resident set size. */
  256. printf("%lu", (UL) resp->ru.ru_maxrss);
  257. break;
  258. case 'O': /* Outputs. */
  259. printf("%lu", resp->ru.ru_oublock);
  260. break;
  261. case 'P': /* Percent of CPU this job got. */
  262. /* % cpu is (total cpu time)/(elapsed time). */
  263. if (resp->elapsed_ms > 0)
  264. printf("%u%%", (unsigned)(vv_ms * 100 / resp->elapsed_ms));
  265. else
  266. printf("?%%");
  267. break;
  268. case 'R': /* Minor page faults (reclaims). */
  269. printf("%lu", resp->ru.ru_minflt);
  270. break;
  271. case 'S': /* System time. */
  272. printf("%u.%02u",
  273. (unsigned)resp->ru.ru_stime.tv_sec,
  274. (unsigned)(resp->ru.ru_stime.tv_usec / 10000));
  275. break;
  276. case 'T': /* System time. */
  277. if (resp->ru.ru_stime.tv_sec >= 3600) /* One hour -> h:m:s. */
  278. printf("%uh %um %02us",
  279. (unsigned)(resp->ru.ru_stime.tv_sec / 3600),
  280. (unsigned)(resp->ru.ru_stime.tv_sec % 3600) / 60,
  281. (unsigned)(resp->ru.ru_stime.tv_sec % 60));
  282. else
  283. printf("%um %u.%02us", /* -> m:s. */
  284. (unsigned)(resp->ru.ru_stime.tv_sec / 60),
  285. (unsigned)(resp->ru.ru_stime.tv_sec % 60),
  286. (unsigned)(resp->ru.ru_stime.tv_usec / 10000));
  287. break;
  288. case 'U': /* User time. */
  289. printf("%u.%02u",
  290. (unsigned)resp->ru.ru_utime.tv_sec,
  291. (unsigned)(resp->ru.ru_utime.tv_usec / 10000));
  292. break;
  293. case 'u': /* User time. */
  294. if (resp->ru.ru_utime.tv_sec >= 3600) /* One hour -> h:m:s. */
  295. printf("%uh %um %02us",
  296. (unsigned)(resp->ru.ru_utime.tv_sec / 3600),
  297. (unsigned)(resp->ru.ru_utime.tv_sec % 3600) / 60,
  298. (unsigned)(resp->ru.ru_utime.tv_sec % 60));
  299. else
  300. printf("%um %u.%02us", /* -> m:s. */
  301. (unsigned)(resp->ru.ru_utime.tv_sec / 60),
  302. (unsigned)(resp->ru.ru_utime.tv_sec % 60),
  303. (unsigned)(resp->ru.ru_utime.tv_usec / 10000));
  304. break;
  305. case 'W': /* Times swapped out. */
  306. printf("%lu", resp->ru.ru_nswap);
  307. break;
  308. case 'X': /* Average shared text size. */
  309. printf("%lu", /*ptok(pagesize,*/ (UL) resp->ru.ru_ixrss / cpu_ticks);
  310. break;
  311. case 'Z': /* Page size. */
  312. printf("%u", pagesize);
  313. break;
  314. case 'c': /* Involuntary context switches. */
  315. printf("%lu", resp->ru.ru_nivcsw);
  316. break;
  317. case 'e': /* Elapsed real time in seconds. */
  318. printf("%u.%02u",
  319. (unsigned)resp->elapsed_ms / 1000,
  320. (unsigned)(resp->elapsed_ms / 10) % 100);
  321. break;
  322. case 'k': /* Signals delivered. */
  323. printf("%lu", resp->ru.ru_nsignals);
  324. break;
  325. case 'p': /* Average stack segment. */
  326. printf("%lu", /*ptok(pagesize,*/ (UL) resp->ru.ru_isrss / cpu_ticks);
  327. break;
  328. case 'r': /* Incoming socket messages received. */
  329. printf("%lu", resp->ru.ru_msgrcv);
  330. break;
  331. case 's': /* Outgoing socket messages sent. */
  332. printf("%lu", resp->ru.ru_msgsnd);
  333. break;
  334. case 't': /* Average resident set size. */
  335. printf("%lu", /*ptok(pagesize,*/ (UL) resp->ru.ru_idrss / cpu_ticks);
  336. break;
  337. case 'w': /* Voluntary context switches. */
  338. printf("%lu", resp->ru.ru_nvcsw);
  339. break;
  340. case 'x': /* Exit status. */
  341. printf("%u", WEXITSTATUS(resp->waitstatus));
  342. break;
  343. }
  344. break;
  345. default: /* *fmt is '\': format escape */
  346. switch (*++fmt) {
  347. default:
  348. /* Unknown \<char> is printed as "?\<char>" */
  349. bb_putchar('?');
  350. bb_putchar('\\');
  351. if (!*fmt) {
  352. /* Trailing -f '...\': GNU time 1.9 prints
  353. * "...?\COMMAND" (it's probably a bug).
  354. */
  355. puts(command[0]);
  356. goto ret;
  357. }
  358. /*FALLTHROUGH*/
  359. case '\\':
  360. bb_putchar(*fmt);
  361. break;
  362. case 't':
  363. bb_putchar('\t');
  364. break;
  365. case 'n':
  366. bb_putchar('\n');
  367. break;
  368. }
  369. break;
  370. }
  371. ++fmt;
  372. }
  373. bb_putchar('\n');
  374. ret: ;
  375. }
  376. /* Run command CMD and return statistics on it.
  377. Put the statistics in *RESP. */
  378. static void run_command(char *const *cmd, resource_t *resp)
  379. {
  380. pid_t pid;
  381. void (*interrupt_signal)(int);
  382. void (*quit_signal)(int);
  383. resp->elapsed_ms = monotonic_ms();
  384. pid = xvfork();
  385. if (pid == 0) {
  386. /* Child */
  387. BB_EXECVP_or_die((char**)cmd);
  388. }
  389. /* Have signals kill the child but not self (if possible). */
  390. //TODO: just block all sigs? and re-enable them in the very end in main?
  391. interrupt_signal = signal(SIGINT, SIG_IGN);
  392. quit_signal = signal(SIGQUIT, SIG_IGN);
  393. resuse_end(pid, resp);
  394. /* Re-enable signals. */
  395. signal(SIGINT, interrupt_signal);
  396. signal(SIGQUIT, quit_signal);
  397. }
  398. int time_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  399. int time_main(int argc UNUSED_PARAM, char **argv)
  400. {
  401. resource_t res;
  402. /* $TIME has lowest prio (-v,-p,-f FMT override it) */
  403. const char *output_format = getenv("TIME") ? : default_format;
  404. char *output_filename;
  405. int output_fd;
  406. int opt;
  407. int ex;
  408. enum {
  409. OPT_v = (1 << 0),
  410. OPT_p = (1 << 1),
  411. OPT_a = (1 << 2),
  412. OPT_o = (1 << 3),
  413. OPT_f = (1 << 4),
  414. };
  415. /* "+": stop on first non-option */
  416. opt = getopt32(argv, "^+" "vpao:f:" "\0" "-1"/*at least one arg*/,
  417. &output_filename, &output_format
  418. );
  419. argv += optind;
  420. if (opt & OPT_v)
  421. output_format = long_format;
  422. if (opt & OPT_p)
  423. output_format = posix_format;
  424. output_fd = STDERR_FILENO;
  425. if (opt & OPT_o) {
  426. #ifndef O_CLOEXEC
  427. # define O_CLOEXEC 0
  428. #endif
  429. output_fd = xopen(output_filename,
  430. (opt & OPT_a) /* append? */
  431. ? (O_CREAT | O_WRONLY | O_CLOEXEC | O_APPEND)
  432. : (O_CREAT | O_WRONLY | O_CLOEXEC | O_TRUNC)
  433. );
  434. if (!O_CLOEXEC)
  435. close_on_exec_on(output_fd);
  436. }
  437. run_command(argv, &res);
  438. /* Cheat. printf's are shorter :) */
  439. xdup2(output_fd, STDOUT_FILENO);
  440. summarize(output_format, argv, &res);
  441. ex = WEXITSTATUS(res.waitstatus);
  442. /* Impossible: we do not use WUNTRACED flag in wait()...
  443. if (WIFSTOPPED(res.waitstatus))
  444. ex = WSTOPSIG(res.waitstatus);
  445. */
  446. if (WIFSIGNALED(res.waitstatus))
  447. ex = WTERMSIG(res.waitstatus);
  448. fflush_stdout_and_exit(ex);
  449. }