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
7USE_TIME(NEWTOY(time, "<1^p", TOYFLAG_USR|TOYFLAG_BIN))
8
9config TIME
10  bool "time"
11  default y
12  depends on TOYBOX_FLOAT
13  help
14    usage: time [-p] 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 mode (ignored)
21*/
22
23#include "toys.h"
24
25void time_main(void)
26{
27  pid_t pid;
28  struct timeval tv, tv2;
29
30  gettimeofday(&tv, NULL);
31  if (!(pid = XVFORK())) xexec(toys.optargs);
32  else {
33    int stat;
34    struct rusage ru;
35    float r, u, s;
36
37    wait4(pid, &stat, 0, &ru);
38    gettimeofday(&tv2, NULL);
39    if (tv.tv_usec > tv2.tv_usec) {
40      tv2.tv_usec += 1000000;
41      tv2.tv_sec--;
42    }
43    r = (tv2.tv_sec-tv.tv_sec)+((tv2.tv_usec-tv.tv_usec)/1000000.0);
44    u = ru.ru_utime.tv_sec+(ru.ru_utime.tv_usec/1000000.0);
45    s = ru.ru_stime.tv_sec+(ru.ru_stime.tv_usec/1000000.0);
46    fprintf(stderr, "real %f\nuser %f\nsys %f\n", r, u, s);
47    toys.exitval = WIFEXITED(stat) ? WEXITSTATUS(stat) : WTERMSIG(stat);
48  }
49}
50