iostream很慢??

在这里,我不得不纠正大家以为iostream很慢的这样一个以讹传讹流毒无穷的错误观念。
大家观察到的iostream慢,通常都是因为C++需要保持对C的IO Library兼容,所以C++的io library是没有buffer的,而且必须一个字符一个字符来读取!
比如说有人蛋疼这么写:
getline(cin, s);
scanf("%d", &i);
这 里getline只能一个字符一个字符读取,假如它一次读了100个字符,只用到了10个,剩下的90个没办法放回stdin里面,这样下面的scanf 就是从错误的位置读取的。所以C++的library为了兼容C,不得不一个字符一个字符读取。这样就导致C++的iostream比较慢。
好在这个行为是可以设置的。cin.sync_with_stdio(false); 这样就会让C++的iostream变快了。当然你如果这么做你得保证没有用到C的io library。
下面是测试:
[xxx@yyy ~]$ cat TestCIO.c && gcc -O3 TestCIO.c -o TestCIO.out
#include <stdio.h>

int main(int argc, char** argv)
{
  char s[1024];
  while(fgets(s,1024,stdin))
  {
    printf("%s",s);
  }
}

[xxx@yyy ~]$ cat TestCXXIO.cpp && g++ -O3 TestCXXIO.cpp -o TestCXXIO.out
#include <iostream>
using namespace std;

int main(int argc, char** argv)
{
  cin.sync_with_stdio(false);
  char s[1024];
  while(cin.getline(s,1024,'\n'))
    cout << s << endl;
}

[xxx@yyy ~]$ time for ((i = 0; i < 10; i++)); do ./TestCIO.out < some_text; done
...........
real    0m7.170s
user    0m0.957s
sys     0m1.623s

[xxx@yyy ~]$ time for ((i = 0; i < 10; i++)); do ./TestCXXIO.out < some_text; done
...........
real    0m7.123s
user    0m0.742s
sys     0m1.737s

两者的速度是一致的。

posted on 2012-01-08 23:25 cutepig 阅读(49) 评论(0) 编辑 收藏

导航

<2012年1月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
2930311234

公告

昵称:cutepig
园龄:4年8个月
粉丝:11
关注:0

搜索

 
 

常用链接

随笔分类(58)

随笔档案(536)

文章档案(1)

我的链接

积分与排名

  • 积分 - 193028
  • 排名 - 443

最新评论

阅读排行榜