We can measure three kinds of process time: wall clock time, user CPU time and system CPU time. Any process can call the times function to get itself
And the above values for terminating child processes.
The structure of buf in the function is as follows:
- #include <sys/times.h>
- clock_t times(struct tms* buf); //If successful, it will return the elapsed clock time on the wall (unit: clock ticks), if wrong, it will return - 1
To get the run time, you must get the relative value. For example, call times, save the return value, call times again at a later time, and subtract from the new return value
- struct tms{
- clock_t tms_utimes; //user cpu time
- clock_t tms_stimes; //system cpu time
- clock_t tms_cutime; //user cpu time, terminated children
- clock_t tms_cstime; //system cpu time, terminated children
- }
Previous return value, the difference is the wall clock time.
All the clock Φ T values returned by this function are transformed into seconds by SC Φ CLK Φ TCK (clock ticks per second returned by the sysconf function).
Operation result:
- #include <stdio.h>
- #include <sys/times.h>
- #include <time.h>
- #include <unistd.h>
- static void pr_times(clock_t,struct tms*,struct tms*);
- static void do_cmd(char *);
- int main(int argc, char *argv[]){
- int i;
- for(i=1; i<argc; i++){
- do_cmd(argv[i]);
- }
- return 0;
- }
- static void do_cmd(char* cmd){
- struct tms tmsstart, tmsend;
- clock_t start, end;
- int status;
- printf("command:%s\n",cmd);
- if((start=times(&tmsstart)) == -1){
- perror("times");
- return;
- }
- if((status = system(cmd))<0){
- perror("system");
- return;
- }
- if((end = times(&tmsend)) == -1){
- perror("times");
- return;
- }
- 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 = sysconf(_SC_CLK_TCK))<0){
- perror("sysconf");
- return;
- }
- 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);
- }
yan@yan-vm:~/apue$ ./a.out "dd if=/dev/zero of=/dev/null bs=1M count=1000"
command:dd if=/dev/zero of=/dev/null bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 0.212456 s, 4.9 GB/s
real: 0.22
user: 0.00
sys: 0.00
child user: 0.01
child sys: 0.20