time.c 13 KB

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