#include <sys/times.h> clock_t times(struct tms *buf); /* Return value: If successful, return elapsed wall clock time (in clock ticks); otherwise, return -1 */ struct tms{ clock_t tms_utime; // user CPU time clock_t tms_stime; // system CPU time clock_t tms_cutime; // user CPU time, terminated children clock_t tms_cstime; // system CPU time, terminated children };
Note that the wall clock time is obtained as the return value, which is measured relative to a time in the past. The two fields for subprocesses in the tms structure contain the values of each subprocess that this process has waited for with the wait function family. All clock_t values returned by this function are converted to seconds using _SC_CLK_TCK (the number of clock ticks per second returned by the sysconf function) (most implementations also provide a getrusage function, which returns the value of the CPU time and additional information indicating resource usage 14 values).
The following program times each shell command and prints the value taken from the tms structure.
#include <stdlib.h> #include <stdio.h> #include <sys/times.h> static void pr_times(clock_t, struct tms *, struct tms *); static void do_cmd(char *); int main(int argc, char *argv[]){ int i; setbuf(stdout, NULL); for(i=1; i<argc; i++) do_cmd(argv[i]); exit(0); } static void do_cmd(char *cmd){ struct tms tmsstart, tmsend; clock_t start, end; int status; printf("\ncommand: %s\n", cmd); if((start=times(&tmsstart)) == -1) printf("times 1 error\n"); if((status=system(cmd)) < 0) printf("system error\n"); if((end=times(&tmsend)) == -1) printf("times 2 error\n"); pr_times(end-start, &tmsstart, &tmsend); } static void pr_times(clock_t real, struct tms *tmsstart, struct tms *tmsend){ static long clktck = 0; if(clktck == 0) if((clktck=sysconf(_SC_CLK_TCK)) < 0) printf("sysconf error\n"); printf(" real: %7.2f\n", real/(double)clktck); printf(" user: %7.2f\n", (tmsend->tms_utime - tmsstart->tms_utime)/(double)clktck); printf(" sys: %7.2f\n", (tmsend->tms_stime - tmsstart->tms_stime)/(double)clktck); printf(" child user: %7.2f\n", (tmsend->tms_cutime - tmsstart->tms_cutime)/(double)clktck); printf(" child sys: %7.2f\n", (tmsend->tms_cstime - tmsstart->tms_cstime)/(double)clktck); }
operation result:
$ ./timesDemo.out "sleep 5" "date>/dev/null" "man bash>/dev/null" command: sleep 5 real: 5.01 user: 0.00 sys: 0.00 child user: 0.00 child sys: 0.00 command: date>/dev/null real: 0.00 user: 0.00 sys: 0.00 child user: 0.00 child sys: 0.00 command: man bash>/dev/null real: 0.28 user: 0.00 sys: 0.00 child user: 0.23 child sys: 0.02
The execution time of the first two commands is fast enough to avoid recording CPU time with reportable precision, but the third command runs a program that takes long enough to process to appear that all the CPU time is in the subprocess, while the shell and The command is executed exactly in the child process.