#define _GNU_SOURCE

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/times.h>
#include <fcntl.h>
#include <err.h>
#include <sys/wait.h>
#include <errno.h>
#include <math.h>

char *clocksToHumanReadable(clock_t c);

int
main(int argc, char *argv[])
{
    clock_t c;
    struct tms tms;
    pid_t pid;
    int status;

    if (argc < 2)
        errx(EXIT_FAILURE, "usage: %s command", program_invocation_name);

    if ((pid = fork()) == -1)
        err(EXIT_FAILURE, "fork");

    if (pid == 0) {
        if (execvp(argv[1], &argv[2]) == -1)
            err(EXIT_FAILURE, "execv");
        exit(EXIT_FAILURE);
    }
    else
        pid = wait(&status);

    c = times(&tms);
    fprintf(stderr, "\n");
    fprintf(stderr, "real\t%s\n", clocksToHumanReadable(
                                        tms.tms_cutime + tms.tms_cstime));
    fprintf(stderr, "user\t%s\n", clocksToHumanReadable(tms.tms_cutime));
    fprintf(stderr, "sys\t%s\n", clocksToHumanReadable(tms.tms_cstime));

    exit(EXIT_SUCCESS);
}

char *
clocksToHumanReadable(clock_t c)
{
    static char buf[35];
    int clocksPerSecond, min;

    clocksPerSecond = sysconf(_SC_CLK_TCK);
    min = c / clocksPerSecond / 60;

    sprintf(buf, "%ld\t%dm%.3fs", (long) c, min, (double) c / clocksPerSecond);
    return buf;
}
