为什么istream / ostream慢 [英] Why is istream/ostream slow

查看:203
本文介绍了为什么istream / ostream慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://channel9.msdn的50:40。 com /事件/ GoingNative / 2013 /写快速代码在Cpp快速 Andrei Alexandrescu做一个笑话关于如何没有有效/慢istream是。

At 50:40 of http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-Quickly Andrei Alexandrescu makes a joke about how not efficient/slow istream is.

我有一个问题,在过去,ostream是慢和fwrite显着更快(减少很多秒,当运行主循环一次),但我从来没有理解为什么,看看它。

I had an issue in the past with ostream being slow and fwrite being significantly faster (reducing many seconds when running the main loop once) but I never understood why nor looked into it.

C ++中istream和ostream缓慢的原因是什么?

What makes istream and ostream slow in C++? or at least slow compared to other things (like fread/fget, fwrite) which would equally satisfied the needs.

推荐答案

实际上, IOStreams不必慢!这是一个问题,以合理的方式实现他们,使他们快速,虽然。大多数标准的C ++库似乎不太关注实现IOStreams。很久以前,当我的 CXXRT 仍然保持时,它的速度与stdio - 正确使用时一样快!

Actually, IOStreams don't have to be slow! It is a matter of implementing them in a reasonable way to make them fast, though. Most standard C++ library don't seem to pay too much attention to implement IOStreams. A long time ago when my CXXRT was still maintained it was about as fast as stdio - when used correctly!

请注意,使用IOStreams布局的用户的性能陷阱很少。以下指南适用于所有IOStream实现,但特别适用于那些被定制为快速的:

Note that there are few performance traps for users laid out with IOStreams, however. The following guidelines apply to all IOStream implementations but especially to those which are tailored to be fast:


  1. 使用 std :: cin , std :: cout 等,你需要调用 std :: sync_with_stdio(false) code>!没有这个调用,需要使用标准流对象来与C的标准流同步。当然,当使用 std :: sync_with_stdio(false)时,假设你不要混合 std :: cin 使用 stdout std :: cout / strong>使用 std :: endl ,因为它强制许多不必要的刷新任何缓冲区。同样,不要设置 std :: ios_base :: unitbuf 或不必要地使用 std :: flush

  2. 创建自己的流缓冲区(OK,很少有用户做),确保它们使用内部缓冲区!处理单个字符会跳过多个条件和一个 virtual 函数,这使得它非常慢。

  1. When using std::cin, std::cout, etc. you need to call std::sync_with_stdio(false)! Without this call, any use of the standard stream objects is required to synchronize with C's standard streams. Of course, when using std::sync_with_stdio(false) it is assumed that you don't mix std::cin with stdin, std::cout with stdout, etc.
  2. Do not use std::endl as it mandates many unnecessary flushes of any buffer. Likewise, don't set std::ios_base::unitbuf or use std::flush unnecessarily.
  3. When creating your own stream buffers (OK, few users do), make sure they do use an internal buffer! Processing individual characters jumps through multiple conditions and a virtual function which makes it hideously slow.

这篇关于为什么istream / ostream慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆