unix环境高级编程-5.8-标准I/O的效率。

来源:互联网 发布:mac版painter2015破解 编辑:程序博客网 时间:2024/04/29 17:56

使用上一节所述的函数。我们能对标准的I/O的效率有所了解。

请看下面的程序

#include "apue.h"int main(void){int c;while((c=getc(stdin))!=EOF){if(putc(c,stdout)==EOF)err_sys("output error");if(ferror(stdin))err_sys("input error");exit(0);}}


运行结果:

进行对getc和putc改写,效果一样的。。。

#include "apue.h"int main(void){int c;while((c=fgetc(stdin))!=EOF){if(fputc(c,stdout)==EOF)err_sys("output error");if(ferror(stdin))err_sys("input error");exit(0);}}

整行读入

#include "apue.h"int main(){        char buf[MAXLINE];        while(fgets(buf,MAXLINE,stdin)!=NULL)        {                if(fputs(buf,stdout)==EOF)                                err_sys("output error");        if(ferror(stdin))                err_sys("input error");        exit(0);        }}


输出结果:

注意5.1的程序和程序清单5-2的程序中,没有显示的关闭标准I/O流。我们知道exit函数将会冲洗任何未写的数据。然后关闭所有打开的流。

书中给出了一个实验。

下表

对于这三个标准的io版,其用户时间都大于表3-2中的最佳read版本,因为在每次读一个字符的标准I/O版本中有一个要执行一亿次的循环。而对每读一行的版本要执行三百万多次循环。在read版本中,其循环只需执行12611次,主要决定了缓冲区的长度

8192字节。

其差别就是在cpu时间和等待I/O结束所消耗的时间。