【黑科技】C++输入输出优化技巧

来源:互联网 发布:promise js 阮一峰 编辑:程序博客网 时间:2024/06/09 20:45

今天下午经过试验(GUOAK,EGG,TYX,WEATAO等人围观),得出以下输入输出优化结论;

对于一个有10000000个随机数字,大小约为38M的文本文件;

输入测试:

1、用scanf()方式读入需要5.01秒

2、用以下方式读入则只需要1.139秒

#include<iostream>#include<cstdio>using namespace std;void read(int &x){x=0;char c=getchar();while(c<'0' || c>'9')c=getchar();while(c>='0' && c<='9'){x=x*10+c-'0';c=getchar();} }int main(){freopen("tt.in","r",stdin);int i,j,k,m,n;for(i=1;i<=10000000;i++)read(n);//for(i=1;i<=10000000;i++)scanf("%d",&n);return 0;}
输出测试:

对于上述文件

1、以printf()方式输出需要18.121秒

2、用以下方式输出则需要1.288秒

#include<iostream>#include<cstdio>using namespace std;void read(int &x){x=0;char c=getchar();while(c<'0' || c>'9')c=getchar();while(c>='0' && c<='9'){x=x*10+c-'0';c=getchar();} }void write(int x){if(x==0){putchar(48);return;}int len=0,dg[20];while(x>0){dg[++len]=x%10;x/=10;}for(int i=len;i>=1;i--)putchar(dg[i]+48);}int main(){freopen("tt.in","r",stdin);freopen("tt.out","w",stdout);int i,j,k,m,n;//for(i=1;i<=10000000;i++){read(n);printf("%d ",n);}for(i=1;i<=10000000;i++){read(n);write(n);putchar(' ');}return 0;}
关于输出优化,罗大神又有了不用开数组的方法:

void write(int x){int y=10,len=1;while(y<=x){y*=10;len++;}while(len--){y/=10;putchar(x/y+48);x%=y;}}



9 0
原创粉丝点击