同步关闭时的cout速度

Ton*_*Joe 5 c++ c++11

我想使用以下代码比较C printfcoutC ++ 的速度cout

#include <iostream>

int main()
{
    for (int i = 0; i < 150000; i++)
        std::cout << "Hello!";
}
Run Code Online (Sandbox Code Playgroud)

和此代码为printf

#include <cstdio>

int main()
{
    for (int i = 0; i < 150000; i++)
        std::printf("Hello!");
}
Run Code Online (Sandbox Code Playgroud)

我运行了两个程序很多次,这就是结果(使用g ++编译器):

cout:17.116 s

printf:9.153秒

因此printf比快两倍cout。我在Stack Overflow中搜索了此行为背后的原因,发现它printfcout它在cout对象中具有功能时要快。但是我也了解到,它cout比较慢,因为它与标准C流同步。

因此,我接下来要做的是使用以下代码关闭所有iostream标准流及其对应的标准C流的同步:

#include <iostream>

int main()
{
    std::ios_base::sync_with_stdio(false);
    for (int i = 0; i < 150000; ++i)
        std::cout << "Hello!";
}
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,这就是我得到的:

printf:9.153秒

cout 同步开启:17.116秒

cout 同步关闭:1.146秒

哇!差异很大!

所以我的问题是:始终关闭同步是一个好习惯吗?

提前致谢。

小智 2

这取决于您期望的输出是否必须按顺序排列。如果您使用输出流混合 C 风格或其他输出。您不想总是关闭同步。

当您不想将其关闭时。

  1. 您将 Cout 与其他流输出函数混合。例如 scanf/printf、gets/puts、getchar/putchar ... ) 和 C++ 风格 IO (cin/cout ... )[ 1 ]

  2. 您正在使用具有良好输出的输出线程。“同时访问同步流(即该函数返回 true 的流)永远不会引入数据竞争:字符是单独读/写的,尽管没有进一步保证线程之间的顺序。除非正确同步,否则这可能会导致线程之间交错字符整个操作都是由程序强制执行的。”[ 1 ]

否则,关闭同步通常就可以了。

另请参阅: http ://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio