3
0

time.c 14 KB

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