time.c 14 KB

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