3
0

time.c 15 KB

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