使用 MS Compiler 的 std::cout 非常慢 [英] Extremely slow std::cout using MS Compiler
问题描述
我正在打印计算的多次迭代的进度,输出实际上是其中最慢的部分,但只有当我使用 Visual C++ 编译器时,MinGW 才能在同一系统上正常工作.
I am printing progress of many iterations of a computation and the output is actually the slowest part of it, but only if I use Visual C++ compiler, MinGW works fine on the same system.
考虑以下代码:
#include <iostream>
#include <chrono>
using namespace std;
#define TO_SEC(Time) \
chrono::duration_cast<chrono::duration<double> >(Time).count();
const int REPEATS = 100000;
int main() {
auto start_time = chrono::steady_clock::now();
for (int i = 1; i <= REPEATS; i++)
cout << '\r' << i << "/" << REPEATS;
double run_time = TO_SEC(chrono::steady_clock::now() - start_time);
cout << endl << run_time << "s" << endl;
}
现在我用 MinGW ("g++ source.cpp -std==c++11") 编译时得到的输出是:
Now the output I get when compiled with MinGW ("g++ source.cpp -std==c++11") is:
100000/100000
0.428025s
现在使用 Visual C++ Compiler 2013 年 11 月(cl.exe source.cpp")编译时得到的输出是:
Now the output I get when compiled with Visual C++ Compiler November 2013 ("cl.exe source.cpp") is:
100000/100000
133.991s
这太荒谬了.我想到的是 VC++ 正在进行不必要的刷新.
Which is quite preposterous. What comes to mind is that VC++ is conducting unnecessary flushes.
有人知道如何防止这种情况发生吗?
Would anybody know how to prevent this?
设置是:
gcc 版本 4.8.2 (GCC),目标 i686-pc-cygwin
gcc version 4.8.2 (GCC), target i686-pc-cygwin
适用于 x86 的 Microsoft (R) C/C++ 优化编译器版本 18.00.21005.1
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.21005.1 for x86
Windows 7 Professional N 64-bit with CPU i7-3630QM, 2.4GHz with 8.00GB RAM
Windows 7 Professional N 64-bit with CPU i7-3630QM, 2.4GHz with 8.00GB RAM
推荐答案
std::cout
在 MSVC 中很慢 (https://web.archive.org/web/20170329163751/https://connect.microsoft.com/VisualStudio/feedback/details/642876/std-wcout-is-ten-times-slower-than-wprintf-performance-bug-in-c-library).
std::cout
in MSVC is slow (https://web.archive.org/web/20170329163751/https://connect.microsoft.com/VisualStudio/feedback/details/642876/std-wcout-is-ten-times-slower-than-wprintf-performance-bug-in-c-library).
这是我们的 C 和 C++ 标准库设计了实现.问题是当打印到控制台(而不是,比如说,被重定向到一个文件),我们的 C默认情况下,也不会缓冲 C++ I/O.这有时被隐藏C I/O 函数像 printf() 和 puts() 临时的事实在工作时启用缓冲.
It is an unfortunate consequence of how our C and C++ Standard Library implementations are designed. The problem is that when printing to the console (instead of, say, being redirected to a file), neither our C nor C++ I/O are buffered by default. This is sometimes concealed by the fact that C I/O functions like printf() and puts() temporarily enable buffering while doing their work.
Microsoft 建议进行此修复(以在 cout/stdout 上启用缓冲):
Microsoft suggests this fix (to enable buffering on cout/stdout):
setvbuf(stdout, 0, _IOLBF, 4096)
你也可以试试:
cout.sync_with_stdio(false);
但可能不会有什么不同.
but probably it won't make a difference.
这篇关于使用 MS Compiler 的 std::cout 非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!