toybox/toys/posix/time.c
<<
>>
Prefs
   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^pv", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_MAYFORK))
   8
   9config TIME
  10  bool "time"
  11  default y
  12  depends on TOYBOX_FLOAT
  13  help
  14    usage: time [-pv] COMMAND...
  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
  27void 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)) fprintf(stderr, "Real time (s): %f\nSystem time (s): %f\n"
  49      "User time (s): %f\nMax RSS (KiB): %ld\nMajor faults: %ld\n"
  50      "Minor faults: %ld\nFile system inputs: %ld\nFile system outputs: %ld\n"
  51      "Voluntary context switches: %ld\nInvoluntary context switches: %ld\n",
  52      r, s, u, ru.ru_maxrss, ru.ru_majflt, ru.ru_minflt, ru.ru_inblock,
  53      ru.ru_oublock, ru.ru_nvcsw, ru.ru_nivcsw);
  54    else fprintf(stderr, "real %f\nuser %f\nsys %f\n", r, u, s);
  55    toys.exitval = WIFEXITED(stat) ? WEXITSTATUS(stat) : WTERMSIG(stat);
  56  }
  57}
  58