这个问题Effective STL中有提过。今天编程时由于涉及到输出的效率,加上闲着没事,所以做了这测试。
测试对象:
1.cout<<
2.ostream_iterator
3.ostreambuf_iterator
4.printf
5.cout.put
6.rdbuf()->sputn
测试平台:
1.6GHz处理器
测试代码:
#include <iostream>
#include <iterator>
#include <cstdio>
#include <ctime>
#include <iomanip>
using namespace std;
int main()
{
/*以10000个'a'作为输出目标*/
char a[10000] = {'a'};
for (char& x : a)
{
x = 'a';
}
clock_t start1, end1, start2, end2, start3, end3, start4, end4, start5, end5, start6, end6;
/*测试ostream_iterator*/
start1 = clock();
copy(a, a + 10000, ostream_iterator<char>(cout));
end1 = clock();
/*测试ostreambuf_iterator*/
start2 = clock();
copy(a, a + 10000, ostreambuf_iterator<char>(cout));
end2 = clock();
/*测试cout<<*/
start3 = clock();
for (char x: a)
cout << x;
end3 = clock();
/*测试printf*/
start4 = clock();
for (char x: a)
printf("%c", x);
end4 = clock();
/*测试cout.put*/
start5 = clock();
for (char x: a)
cout.put(x);
end5 = clock();
/*测试rdbuf()->sputn*/
start6 = clock();
cout.rdbuf()->sputn(a, 10000);
end6 = clock();
cout << endl;
cout << setw(25) << "ostream_iterator: " << static_cast<double>(end1 - start1) / CLOCKS_PER_SEC << " seconds"<< endl;
cout << setw(25) << "ostreambuf_iterator: " << static_cast<double>(end2 - start2) / CLOCKS_PER_SEC << " seconds"<< endl;
cout << setw(25) << "cout<<: " << static_cast<double>(end3 - start3) / CLOCKS_PER_SEC << " seconds"<< endl;
cout << setw(25) << "printf: " << static_cast<double>(end4 - start4) / CLOCKS_PER_SEC << " seconds"<< endl;
cout << setw(25) << "cout.put: " << static_cast<double>(end5 - start5) / CLOCKS_PER_SEC << " seconds"<< endl;
cout << setw(25) << "rdbuf()->sputn: " << static_cast<double>(end6 - start6) / CLOCKS_PER_SEC << " seconds"<< endl;
return 0;
}
测试结果:
1.用MinGW编译
ostream_iterator: | 5.806 seconds |
ostreambuf_iterator: | 0.142 seconds |
cout<<: | 5.812 seconds |
printf: | 5.673 seconds |
cout.put: | 5.752 seconds |
rdbuf()->sputn: | 0.118 seconds |
2.用Borland C++编译
ostream_iterator: | 5.569 seconds |
ostreambuf_iterator: | 0.203 seconds |
cout<<: | 4.789 seconds |
printf: | 4.493 seconds |
cout.put: | 4.555 seconds |
rdbuf()->sputn: | 0.141 seconds |
3.用VS2012编译
ostream_iterator: | 4.809 seconds |
ostreambuf_iterator: | 4.659seconds |
cout<<: | 4.956 seconds |
printf: | 5.848 seconds |
cout.put: | 6.976 seconds |
rdbuf()->sputn: | 6.793 seconds |
果然,用ostreambuf_iterator和rdbuf()->sputn来进行输出的确快很多,但不同的STL实现速度提升会不同,如VS2012就提升不明显了(例外?)。