📄 p7-2.c
字号:
#include <stdio.h>#include <sys/types.h>#include <sys/times.h>#include <math.h>#include <sys/wait.h>#include <unistd.h>#define KIDNUM 3void work(int);void tell_times(struct tms *, clock_t, clock_t);int main (void){ clock_t start, stop; struct tms buffer; int i; pid_t pid; start = times(&buffer); printf(" start time: %u (ticks)\n",start); printf(" utime: %d (ticks), stime: %d (ticks)\n" "cutime: %d (ticks), cstime: %d (ticks)\n", buffer.tms_utime, buffer.tms_stime, buffer.tms_cutime, buffer.tms_cstime); for (i = 1; i <= KIDNUM; i++) if( !(pid = fork()) ){ /* 子进程代码 */ work(i); exit(0); } /* 父进程代码 */ work(KIDNUM+1); for(i = 0; i < KIDNUM; i++){ /* 等待子进程并计算子进程所花的时间 */ pid = wait(NULL); printf("Child %d, now terminate.\n", pid); stop = times(&buffer); tell_times(&buffer, start, stop); } /* 计算父进程的总时间 */ printf("Parent Done. \n"); stop = times(&buffer); tell_times(&buffer, start, stop); return 0;}void work(int k) /* 模拟工作 */{ FILE *f; int i; double x=4.5; f = tmpfile(); for(i = 0; i < k*100000; i++){ fprintf(f,"Do some output\n"); if(ferror(f)){ fprintf(stderr,"Error writing to temorary file\n"); exit(1); } } for(i=0;i<k*100000;i++) x=log(x*x+3.21);}void tell_times(struct tms *buf, clock_t start, clock_t stop){ printf("stop time: %u, total time: %d (ticks)\n", stop, stop-start); printf(" wall time: %lf(seconds)\n", (double)(stop - start)/(double)sysconf(_SC_CLK_TCK)); printf(" utime: %d (ticks), stime: %d (ticks)\n" " cutime: %d (ticks), cstime: %d (ticks)\n", buf->tms_utime, buf->tms_stime, buf->tms_cutime, buf->tms_cstime); printf(" user cpu time: %lf(seconds)\n", (double)(buf->tms_utime+buf->tms_cutime) /(double)sysconf(_SC_CLK_TCK)); return;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -