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

今天下午经过试验(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;}
}



评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值