+#include <stdio.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <errno.h>
+
+#define eprintf(...) fprintf(stderr, __VA_ARGS__)
+#define FARG_TIMEVAL(tv) tv.tv_sec, tv.tv_usec
+#define FSTR_TIMEVAL "%li.%06li"
+
+int main(int argc, char **argv) {
+ #define CHECK_USAGE if (argc < 2) return eprintf("invocation: rusage_precise [--machine-readable] <command> [<args...>]\n"), 1;
+ CHECK_USAGE
+ int machine_readable = 0;
+ if (!strcmp(argv[1], "--machine-readable")) machine_readable = 1, argv++, argc--;
+ CHECK_USAGE
+
+ pid_t child = fork();
+ if (child == -1) return perror("fork failed"), 1;
+ if (child == 0) {
+ execvp(argv[1], argv+1);
+ return perror("execvp failed"), 1;
+ }
+
+ int status;
+ struct rusage ru;
+ errno = 0;
+ if (wait4(child, &status, 0, &ru) != child) return perror("wait4 failed"), 1;
+
+ if (machine_readable) {
+ eprintf(FSTR_TIMEVAL "\t" FSTR_TIMEVAL "\t%li\t%li\t%li\t%li\t%li\t%li\t%li\n",
+ FARG_TIMEVAL(ru.ru_utime), FARG_TIMEVAL(ru.ru_stime),
+ ru.ru_maxrss, ru.ru_minflt, ru.ru_majflt,
+ ru.ru_inblock, ru.ru_oublock, ru.ru_nvcsw,
+ ru.ru_nivcsw);
+ } else {
+ eprintf(" user CPU (s): " FSTR_TIMEVAL "\n", FARG_TIMEVAL(ru.ru_utime));
+ eprintf(" system CPU (s): " FSTR_TIMEVAL "\n", FARG_TIMEVAL(ru.ru_stime));
+ eprintf(" max RSS size (kB): %li\n", ru.ru_maxrss);
+ eprintf(" minor faults: %li\n", ru.ru_minflt);
+ eprintf(" major faults: %li\n", ru.ru_majflt);
+ eprintf(" fs inblocks: %li\n", ru.ru_inblock);
+ eprintf(" fs outblocks: %li\n", ru.ru_oublock);
+ eprintf(" voluntary switches: %li\n", ru.ru_nvcsw);
+ eprintf("involuntary switches: %li\n", ru.ru_nivcsw);
+ }
+ return 0;
+}