输出流效率测试

这个问题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_iteratorrdbuf()->sputn来进行输出的确快很多,但不同的STL实现速度提升会不同,如VS2012就提升不明显了(例外?)。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值