I am NOT posting this as a suggestion for implementation. I just find this
quite interesting, so I am posting it here for anyone who might also find it
interesting. Feel free to cherry-pick some parts, or take the whole thing.
The attached patch makes the following changes to the `time' command:
1) Adds a compile-time choice to use CLOCK_MONOTONIC, if available.
As a result, now we have a good timing accuracy on Cygwin too.
2) If shell-var TIMEWARMUP exists, and if it is set to an integer N>0, then
`time' runs a warmup loop N times, in hope to awaken idled-down CPUs before
timing the command. This can improve the accuracy of the measurement.
The observed benefit of this varies widely from one type of CPU to another.
(Down to no effect whatsoever on some.)
3) If shell-var TIMEREPEAT exists, and if it is set to an integer N>1, then
`time' runs the command N times before taking the final clock-reading.
4) `time' leaves the elapsed time (wall clock) result in shell-var TIMERESULT,
according to the "%[p][l]R" portion of the TIMEFORMAT variable.
5) By moving the "before" and "after" clock-readings as close as possible to
the
command that's being timed, it noticeably increases the accuracy of the results
when measuring some fast, short-lasting commands.
6) Three bugs were fixed. A few other minor bugs are waiting for input from
the developer.
7) Cleaned up some code for which I couldn't find a way to leave it as-is.
I left comments about the necessity of the changes.
8) There's one outstanding problem: If "(posixly_correct && nullcmd)", and if
compiled with CLOCK_MONOTONIC then `time' will display a result equivalent to
`uptime', rather than the time since the shell was started. I'll fix that.
But currently "if (posixly_correct && nullcmd)" is broken anyway, should the
compiler fall back to something other than "defined (HAVE_GETTIMEOFDAY)".
So, these are the vars that this version is using, if they exist...
TIMEFORMAT
TIMEWARMUP
TIMEREPEAT
TIMERESULT
(At this point I can picture Greg Wooledge crying "This is preposterous!",
and his head exploding.:)
Tested on Slackware Linux, and on Alpine Linux.
Patch (apply with `patch -p0'):