ACM读入输出优化

inline int read()  
{  
    char ch;
	bool flag = false;
    int a = 0;  
    while(!((((ch = getchar()) >= '0') && (ch <= '9')) || (ch == '-')));  
    if(ch != '-')
	{
		a *= 10;
		a += ch - '0';  
	}
	else
	{
		flag = true;
	}
    while(((ch = getchar()) >= '0') && (ch <= '9'))
	{
		a *= 10;
		a += ch - '0';
	}	
	if(flag)
	{
		a = -a;
	}
    return a;  
}  
void write(int a)  
{  
	if(a < 0)
	{
		putchar('-');
		a = -a;
	}
    if(a >= 10)
	{
		write(a / 10);
	}		
    putchar(a % 10 + '0');  
}  

测试:

数据生成

#include <iostream>
#include <cstdio>
#include <windows.h>
#include <cstdlib>
#include <ctime>
using namespace std;
const int MAXN = 1000000;

int main()
{
	freopen("in.txt", "w", stdout);
	srand((unsigned)time(NULL));
	for (int i = 1; i <= MAXN; i++)
	{
		printf("%d\n", rand());
	}
	return 0;
}

#include <iostream>
#include <cstdio>
#include <windows.h>
#include <cstdlib>
#include <ctime>
using namespace std;
#pragma warning(disable : 4996)
const int MAXN = 1000000;

inline int read()  
{  
	char ch;
	bool flag = false;
	int a = 0;  
	while(!((((ch = getchar()) >= '0') && (ch <= '9')) || (ch == '-')));  
	if(ch != '-')
	{
		a *= 10;
		a += ch - '0';  
	}
	else
	{
		flag = true;
	}
	while(((ch = getchar()) >= '0') && (ch <= '9'))
	{
		a *= 10;
		a += ch - '0';
	}	
	if(flag)
	{
		a = -a;
	}
	return a;  
}  
void write(int a)  
{  
	if(a < 0)
	{
		putchar('-');
		a = -a;
	}
	if(a >= 10)
	{
		write(a / 10);
	}		
	putchar(a % 10 + '0');  
}  

void test1()
{
	int x;
	DWORD start_time, end_time;
	start_time = GetTickCount();
	for (int i = 1; i <= MAXN; i++)
	{
		x = read();
		//write(x);
		//putchar('\n');
	}
	end_time = GetTickCount();
	printf("%lf\n", (end_time - start_time) / 1000.0);
}

void test2()
{
	int x;
	DWORD start_time, end_time;
	start_time = GetTickCount();
	for (int i = 1; i <= MAXN; i++)
	{
		scanf("%d", &x);
		//printf("%d", x);
		//putchar('\n');
	}
	end_time = GetTickCount();
	printf("%lf\n", (end_time - start_time) / 1000.0);
}

int main()
{
	freopen("in.txt", "r", stdin);
	test1();
	test2();
	return 0;
}


单纯进行读入操作:

0.546000
2.340000
请按任意键继续. . .





原文地址:https://www.cnblogs.com/lgh1992314/p/5835002.html