From 16b9f7cd0f25db8f34dea2ece267f47b72a06099 Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Sun, 28 Nov 2021 03:35:13 -0600 Subject: [PATCH] Make time -p output exact posix format, remove TOYBOX_FLOAT dependency, make -pv switch each other off. --- toys/posix/time.c | 60 +++++++++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/toys/posix/time.c b/toys/posix/time.c index eae65e55..951a53d7 100644 --- a/toys/posix/time.c +++ b/toys/posix/time.c @@ -4,12 +4,11 @@ * * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/time.html -USE_TIME(NEWTOY(time, "<1^pv", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_MAYFORK)) +USE_TIME(NEWTOY(time, "<1^pv[-pv]", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_MAYFORK)) config TIME bool "time" default y - depends on TOYBOX_FLOAT help usage: time [-pv] COMMAND... @@ -17,41 +16,50 @@ config TIME (real = clock on the wall, user = cpu used by command's code, system = cpu used by OS on behalf of command.) - -p POSIX format output (default) + -p POSIX format output -v Verbose */ #define FOR_time #include "toys.h" + void time_main(void) { - pid_t pid; struct timeval tv, tv2; + struct rusage ru; + long long sec[3]; + int stat, ii, idx, nano[3]; + pid_t pid; + char *label[] = {"\nreal"+!!FLAG(p), "user", "sys"}, + tab = toys.optflags ? ' ' : '\t'; + if (FLAG(v)) + memcpy(label, (char *[]){"Real", "User", "System"}, 3*sizeof(char *)); gettimeofday(&tv, NULL); if (!(pid = XVFORK())) xexec(toys.optargs); - else { - int stat; - struct rusage ru; - float r, u, s; - - wait4(pid, &stat, 0, &ru); - gettimeofday(&tv2, NULL); - if (tv.tv_usec > tv2.tv_usec) { - tv2.tv_usec += 1000000; - tv2.tv_sec--; - } - r = (tv2.tv_sec-tv.tv_sec)+((tv2.tv_usec-tv.tv_usec)/1000000.0); - u = ru.ru_utime.tv_sec+(ru.ru_utime.tv_usec/1000000.0); - s = ru.ru_stime.tv_sec+(ru.ru_stime.tv_usec/1000000.0); - if (FLAG(v)) fprintf(stderr, "Real time (s): %f\nSystem time (s): %f\n" - "User time (s): %f\nMax RSS (KiB): %ld\nMajor faults: %ld\n" - "Minor faults: %ld\nFile system inputs: %ld\nFile system outputs: %ld\n" - "Voluntary context switches: %ld\nInvoluntary context switches: %ld\n", - r, s, u, ru.ru_maxrss, ru.ru_majflt, ru.ru_minflt, ru.ru_inblock, - ru.ru_oublock, ru.ru_nvcsw, ru.ru_nivcsw); - else fprintf(stderr, "\nreal\t%f\nuser\t%f\nsys\t%f\n", r, u, s); - toys.exitval = WIFEXITED(stat) ? WEXITSTATUS(stat) : WTERMSIG(stat); + wait4(pid, &stat, 0, &ru); + gettimeofday(&tv2, NULL); + if (tv.tv_usec > tv2.tv_usec) { + tv2.tv_usec += 1000000; + tv2.tv_sec--; } + sec[0] = tv2.tv_sec-tv.tv_sec, nano[0] = tv2.tv_usec-tv.tv_usec; + sec[1] = ru.ru_utime.tv_sec, nano[1] = ru.ru_utime.tv_usec; + sec[2] = ru.ru_stime.tv_sec, nano[2] = ru.ru_stime.tv_usec; + for (ii = idx = 0; ii<3; ii++) { + if (!toys.optflags) sec[ii] = (sec[ii]+500)/1000; + idx += sprintf(toybuf+idx, "%s%s%c%lld.%0*d\n", label[ii], + FLAG(v) ? " time (s):" : "", tab, sec[ii], + 3<