3
0

time.c 15 KB

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