• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* time.c - time a simple command
2  *
3  * Copyright 2013 Rob Landley <rob@landley.net>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/time.html
6 
7 USE_TIME(NEWTOY(time, "<1^pv[-pv]", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_MAYFORK))
8 
9 config TIME
10   bool "time"
11   default y
12   help
13     usage: time [-pv] COMMAND...
14 
15     Run command line and report real, user, and system time elapsed in seconds.
16     (real = clock on the wall, user = cpu used by command's code,
17     system = cpu used by OS on behalf of command.)
18 
19     -p	POSIX format output
20     -v	Verbose
21 */
22 
23 #define FOR_time
24 #include "toys.h"
25 
26 
time_main(void)27 void time_main(void)
28 {
29   struct timespec ts, ts2;
30   struct rusage ru;
31   long long sec[3];
32   int stat, ii, idx, nano[3];
33   pid_t pid;
34   char *labels[] = {"\nreal"+FLAG(p), "user", "sys"}, **label = labels,
35        *vlabels[] ={"Real", "User", "System"}, tab = toys.optflags ? ' ' : '\t';
36 
37   if (FLAG(v)) label = vlabels;
38   clock_gettime(CLOCK_MONOTONIC, &ts);
39   if (!(pid = XVFORK())) xexec(toys.optargs);
40   wait4(pid, &stat, 0, &ru);
41   clock_gettime(CLOCK_MONOTONIC, &ts2);
42   sec[0] = nanodiff(&ts, &ts2);
43   nano[0] = (sec[0] % 1000000000)/(toys.optflags ? 1000 : 1000000);
44   sec[0] /= 1000000000;
45   sec[1] = ru.ru_utime.tv_sec, nano[1] = ru.ru_utime.tv_usec;
46   sec[2] = ru.ru_stime.tv_sec, nano[2] = ru.ru_stime.tv_usec;
47   for (ii = idx = 0; ii<3; ii++)
48     idx += sprintf(toybuf+idx, "%s%s%c%lld.%0*d\n", label[ii],
49                    FLAG(v) ? " time (s):" : "", tab, sec[ii],
50                    6>>!toys.optflags, nano[ii]);
51   if (FLAG(v)) idx += sprintf(toybuf+idx,
52     "Max RSS (KiB): %ld\nMajor faults: %ld\n"
53     "Minor faults: %ld\nFile system inputs: %ld\nFile system outputs: %ld\n"
54     "Voluntary context switches: %ld\nInvoluntary context switches: %ld\n",
55     ru.ru_maxrss, ru.ru_majflt, ru.ru_minflt, ru.ru_inblock,
56     ru.ru_oublock, ru.ru_nvcsw, ru.ru_nivcsw);
57   writeall(2, toybuf, idx);
58 
59   toys.exitval = WIFEXITED(stat) ? WEXITSTATUS(stat) : WTERMSIG(stat);
60 }
61