您的位置:首页 > 其它

《算法竞赛入门经典》第三章习题

2013-06-06 17:44 288 查看
做性能测试。题目是“直接输出”:输入不超过1000行字符串,然后直接输出。每行都是长度不超过10000的字符串,包含大写字母和小写字母,不包括任意空白(如空格、TAB)。用C++来测试。《算法竞赛入门经典》第47页。

首先我写了一段程序生成测试数据,即一些个随机字母:(可以正确生成)

1 //生成测试数据
2 #include<iostream>
3 #include<string>
4 #include<cstdlib>
5 #include<fstream>
6 #define COLUMN 10000 //the number of character in each rows
7 #define ROW 1000 //the number of rows
8 using namespace std;
9 ofstream fout("data.txt");
int main()
{
int i,j;
char c;
int a,b;
int flag=1;
for(i=0;i<ROW;i++)
{
for(j=0;j<COLUMN;j++)
{
a=rand()%26;
b=(rand()%2==0)?65:97;
c=a+b;
fout<<c;
}
fout<<'\n';
}
return 0;
}

然后我改写C++输入输出,用读文件的方式: (测试结果,Time used: 0)

1 #include<iostream>
2 #include<fstream>
3 #include<ctime>
4 using namespace std;
5 ifstream fin("data.txt");
6 ofstream fout("dataout.txt");
7 int main()
8 {
9 string s;
while(fin>>s)
fout<<s<<"\n";
double t;
t=clock()/CLOCKS_PER_SEC;
cout<<"Time used:"<<t;
return 0;
}

测试getchar方式的I/O效率,这次选择重定向的方式读写文件,因为我也不知道getchar怎么改写读文件的方式。网上不是说getchar是从stdin读入的吗?!

测试Time used 也是0

1 #define LOCAL
2 #include<stdio.h>
3 #include<time.h>
4 int main()
5 {
6 #ifdef LOCAL
7 freopen("data.txt","r",stdin);
8 freopen("dataout.txt","w",stdout);
9 #endif

int ch;
while((ch=getchar())!=EOF)
{
putchar(ch);
}
double t;
t=clock()/CLOCKS_PER_SEC;
printf("Time used: %lf",t);
return 0;
}

之后
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: