ewx: (geek)
[personal profile] ewx
richard@araminta:~$ cat busy.c
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv) {
  struct timeval now, end;
  sleep(atoi(argv[1]));
  gettimeofday(&now, NULL);
  end = now;
  end.tv_sec += atoi(argv[2]);
  while(now.tv_sec < end.tv_sec || now.tv_usec < end.tv_usec)
    gettimeofday(&now, NULL);
  return 0;
}

This programs sleeps for a number of seconds and then busy-waits for a number of seconds.

richard@araminta:~$ time ./busy 0 1 | time ./busy 1 2 | time ./busy 4 3
0.63user 1.36system 0:03.00elapsed 66%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+133minor)pagefaults 0swaps
1.00user 1.99system 0:07.00elapsed 42%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+133minor)pagefaults 0swaps

real    0m7.016s
user    0m1.932s
sys     0m4.088s

Superficially it would seem that:

  • busy 0 1 slept 1s and busy-waited 2s
  • busy 1 2 slept 4s and busy-waited 3s
  • busy 4 3 slept 2s and busy-waited 6s

Of course this isn't the case at all, and the different output formats are a hint as to what's really going on. Bash interpreted the first time as applying to the whole pipeline (which does indeed survive for 7s and consume 6s of CPU) while the second and third only apply to the individual commands. The whole-pipeline output of course has to appear last since the computer can't predict the future.

In other words, the actual grammar honored by the shell differs sharply from the natural reading of the command. Bash's interpretation is both documented (in man bash) and allowed by a weird exception in the specification, but if you were naively expecting time to behave like every single other command, you'll be quite surprised (if you notice at all). If you don't notice then you'll misled into thinking that the wrong element of your pipeline needs optimizing.

Allowing time at the start of (some or all) compound commands would have been less surprising and more useful, and still allowed timing whole pipelines (when bracketed).

February 2025

S M T W T F S
      1
2345678
9101112131415
16171819202122
232425262728 

Most Popular Tags

Expand Cut Tags

No cut tags