《算法竞赛入门经典》第三章习题
做性能测试。题目是“直接输出”:输入不超过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");
10 int main()
11 {
12 int i,j;
13 char c;
14 int a,b;
15 int flag=1;
16 for(i=0;i<ROW;i++)
17 {
18 for(j=0;j<COLUMN;j++)
19 {
20 a=rand()%26;
21 b=(rand()%2==0)?65:97;
22 c=a+b;
23 fout<<c;
24 }
25 fout<<'\n';
26 }
27 return 0;
28 }
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");
10 int main()
11 {
12 int i,j;
13 char c;
14 int a,b;
15 int flag=1;
16 for(i=0;i<ROW;i++)
17 {
18 for(j=0;j<COLUMN;j++)
19 {
20 a=rand()%26;
21 b=(rand()%2==0)?65:97;
22 c=a+b;
23 fout<<c;
24 }
25 fout<<'\n';
26 }
27 return 0;
28 }
然后我改写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;
10 while(fin>>s)
11 fout<<s<<"\n";
12 double t;
13 t=clock()/CLOCKS_PER_SEC;
14 cout<<"Time used:"<<t;
15 return 0;
16 }
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;
10 while(fin>>s)
11 fout<<s<<"\n";
12 double t;
13 t=clock()/CLOCKS_PER_SEC;
14 cout<<"Time used:"<<t;
15 return 0;
16 }
测试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
10
11 int ch;
12 while((ch=getchar())!=EOF)
13 {
14 putchar(ch);
15 }
16 double t;
17 t=clock()/CLOCKS_PER_SEC;
18 printf("Time used: %lf",t);
19 return 0;
20 }
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
10
11 int ch;
12 while((ch=getchar())!=EOF)
13 {
14 putchar(ch);
15 }
16 double t;
17 t=clock()/CLOCKS_PER_SEC;
18 printf("Time used: %lf",t);
19 return 0;
20 }
之后