加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用MS Compiler极慢的std :: cout

发布时间:2020-12-16 09:51:21 所属栏目:百科 来源:网络整理
导读:我正在打印计算的多次迭代的进度,输出实际上是它的最慢部分,但只有当我使用Visual C编译器时,MinGW才能在同一系统上正常工作. 考虑以下代码: #include iostream#include chronousing namespace std;#define TO_SEC(Time) chrono::duration_castchrono::du
我正在打印计算的多次迭代的进度,输出实际上是它的最慢部分,但只有当我使用Visual C编译器时,MinGW才能在同一系统上正常工作.

考虑以下代码:

#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”)编译时得到的输出是:

100000/100000 
0.428025s

现在,使用Visual C Compiler 2013年11月(“cl.exe source.cpp”)编译时得到的输出是:

100000/100000
133.991s

这是非常荒谬的.我想到的是VC正在进行不必要的冲洗.

有人会知道如何防止这种情况吗?

编辑:设置是:

gcc版本4.8.2(GCC),目标i686-pc-cygwin

适用于x86的Microsoft(R)C/C++优化编译器版本18.00.21005.1

Windows 7 Professional N 64位,CPU i7-3630QM,2.4GHz,内存8.00GB

解决方法

MSVC中的std :: cout很慢( http://connect.microsoft.com/VisualStudio/feedback/details/642876/std-wcout-is-ten-times-slower-than-wprintf-performance-bug-in-c-library).

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上启用缓冲):

setvbuf(stdout,_IOLBF,4096)

你也可以尝试:

cout.sync_with_stdio(false);

但可能它不会有所作为.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读