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", TOYFLAG_USR|TOYFLAG_BIN))
8 
9 config TIME
10   bool "time"
11   default y
12   depends on TOYBOX_FLOAT
13   help
14     usage: time [-pv] COMMAND [ARGS...]
15 
16     Run command line and report real, user, and system time elapsed in seconds.
17     (real = clock on the wall, user = cpu used by command's code,
18     system = cpu used by OS on behalf of command.)
19 
20     -p	POSIX format output (default)
21     -v	Verbose
22 */
23 
24 #define FOR_time
25 #include "toys.h"
26 
time_main(void)27 void time_main(void)
28 {
29   pid_t pid;
30   struct timeval tv, tv2;
31 
32   gettimeofday(&tv, NULL);
33   if (!(pid = XVFORK())) xexec(toys.optargs);
34   else {
35     int stat;
36     struct rusage ru;
37     float r, u, s;
38 
39     wait4(pid, &stat, 0, &ru);
40     gettimeofday(&tv2, NULL);
41     if (tv.tv_usec > tv2.tv_usec) {
42       tv2.tv_usec += 1000000;
43       tv2.tv_sec--;
44     }
45     r = (tv2.tv_sec-tv.tv_sec)+((tv2.tv_usec-tv.tv_usec)/1000000.0);
46     u = ru.ru_utime.tv_sec+(ru.ru_utime.tv_usec/1000000.0);
47     s = ru.ru_stime.tv_sec+(ru.ru_stime.tv_usec/1000000.0);
48     if (FLAG(v)) {
49       fprintf(stderr, "Real time (s): %f\n"
50                       "System time (s): %f\n"
51                       "User time (s): %f\n"
52                       "Max RSS (KiB): %ld\n"
53                       "Major faults: %ld\n"
54                       "Minor faults: %ld\n"
55                       "File system inputs: %ld\n"
56                       "File system outputs: %ld\n"
57                       "Voluntary context switches: %ld\n"
58                       "Involuntary context switches: %ld\n", r, u, s,
59               ru.ru_maxrss, ru.ru_majflt, ru.ru_minflt, ru.ru_inblock,
60               ru.ru_oublock, ru.ru_nvcsw, ru.ru_nivcsw);
61     } else fprintf(stderr, "real %f\nuser %f\nsys %f\n", r, u, s);
62     toys.exitval = WIFEXITED(stat) ? WEXITSTATUS(stat) : WTERMSIG(stat);
63   }
64 }
65