Loading

提高标准输入输出流的速度

在刷leetcode时,看到前面快的solution加上了如下代码:

static int __ = [](){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return 0;
}();

自己加上后,发现速度提升不少,百度查了一下,上面避免了两个因素。

std::ios::sync_with_stdio(false);

iostream默认是与stdio关联在一起的,以使两者同步,因此消耗了iostream不少性能。C++中的std :: cin和std :: cout为了兼容C,保证在代码中同时出现std :: cin和scanf或std :: cout和printf时输出不发生混乱,所以C++用一个流缓冲区来同步C的标准流。通过std :: ios_base :: sync_with_stdio函数设置为false后可以解除这种同步,让std :: cin和std :: cout不再经过缓冲区,iostream的性能就会提高了很多倍。因此,当解除同步之后,注意不要与scanf和printf混用以免出现问题。[1]

std::cin.tie(nullptr);

std :: cin默认是与std :: cout绑定的,所以每次操作的时候(也就是调用”<<”或者”>>”)都要刷新(调用flush),这样增加了IO的负担,通过tie(nullptr)来解除std :: cin和std :: cout之间的绑定,来降低IO的负担使效率提升。[2]

参考

【1】https://blog.csdn.net/Canger_/article/details/85787436
【2】https://blog.csdn.net/b__t__t/article/details/84868841

posted @ 2019-12-23 19:21  FANG_YANG  阅读(473)  评论(0编辑  收藏  举报