3
0

time.c 14 KB

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