C++ 快读 [int] 代码与分析以及速度对比

顾名思义,快速读入。

如有不妥,请指正

 

你需要了解:

  1. inline内联函数:免去调用,相当于直接在函数处,效率高
  2. 没了

上代码 

#include<iostream>
#include<cstring>
using namespace std;
inline int read()
{
    int s=0,w=1;
    char ch=getchar();//读入 
    while(ch<'0'||ch>'9')//读掉其它字符 
    {
    	if(ch=='-')//w判断正负 
    	{
			w=-w;
			ch=getchar();
		}
	}
    while(ch>='0'&&ch<='9')
	{
		s*=10;//腾出个位 
		s+=(int)ch-'0';//个位加上 转的数字 
		ch=getchar();
	}
    return s*w;
}
int main()
{
	int a;
	a=read();
	return 0;
}

加上时间测试:

快读程序:

#include<iostream>
#include<cstring>
#include<ctime>
using namespace std;
clock_t a1,a2;
inline int read()
{
    int s=0,w=1;
    char ch=getchar();//读入 
    while(ch<'0'||ch>'9')//读掉其它字符 
    {
    	if(ch=='-')//w判断正负 
    	{
			w=-w;
			ch=getchar();
		}
	}
    while(ch>='0'&&ch<='9')
	{
		s*=10;//腾出个位 
		s+=(int)ch-'0';//个位加上 转的数字 
		ch=getchar();
	}
    return s*w;
}
int main()
{
	freopen("a.txt","r",stdin);
	int a;
	a1=clock();
	for(int i=0;i<100000;++i)
		a=read();
	a2=clock();
	cout<<(double)(a2-a1)/CLOCKS_PER_SEC;
	return 0;
}

 cin程序:

#include<iostream>
#include<cstring>
#include<ctime>
using namespace std;
clock_t a1,a2;
inline int read()
{
    int x;
    cin>>x;
    return x;
}
int main()
{
	freopen("a.txt","r",stdin);
	int a;
	a1=clock();
	for(int i=0;i<100000;++i)
		a=read();
	a2=clock();
	cout<<(double)(a2-a1)/CLOCKS_PER_SEC;
	return 0;
}

 scanf程序:

#include<iostream>
#include<cstring>
#include<ctime>
using namespace std;
clock_t a1,a2;
inline int read()
{
    int x;
    scanf("%d",&x);
    return x;
}
int main()
{
	freopen("a.txt","r",stdin);
	int a;
	a1=clock();
	for(int i=0;i<100000;++i)
		a=read();
	a2=clock();
	cout<<(double)(a2-a1)/CLOCKS_PER_SEC;
	return 0;
}

a.txt内容:

1000000个2147483647

快读结果:

 

快读5次结果/秒
12345
0.0350.0340.0380.0360.035

 

 

scanf结果:

scanf5次结果/秒
12345
0.0720.0720.0710.0720.073

 

cin结果

cin5次结果/秒
12345
0.1260.140.1240.1240.125

结果显而易见

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值