zoukankan      html  css  js  c++  java
  • cpp输入输出加速

    cpp输入输出加速

    std::ios::sync_with_stdio(false);
    

    解释:这个函数是一个“是否兼容stdio”的开关,C++为了兼容C,保证程序在使用了std::printf和std::cout的时候不发生混乱,将输出流绑到了一起。

    cin,cout之所以效率低,是因为先把要输出的东西存入缓冲区,再输出,导致效率降低,而这段语句可以来打消iostream的输入 输出缓存,可以节省许多时间,使效率与scanf与printf相差无几,还有应注意的是scanf与printf使用的头文件应是stdio.h而不是 iostream。
    我们可以在IO之前将stdio解除绑定,这样做了之后要注意不要同时混用cout和printf 之类。
    

    tie是将两个stream绑定的函数,空参数的话返回当前的输出流指针。
    在默认的情况下cin绑定的是cout,每次执行 << 操作符的时候都要调用flush,这样会增加IO负担。可以通过tie(0)(0表示NULL)来解除cin与cout的绑定,进一步加快执行效率。

        #include <iostream>
        #include <fstream>
    
        int main(int argc, char *argv[])
        {
        std::ostream *prevstr;
        std::ofstream ofs;
        ofs.open("test.txt");
        std::cout << "tie example:
    ";
        // 直接输出到屏幕
        *std::cin.tie() << "This is inserted into cout
    ";
        // 空参数调用返回默认的output stream,也就是cout
        prevstr = std::cin.tie(&ofs);
        // cin绑定ofs,返回原来的output stream
        *std::cin.tie() << "This is inserted into the file
    ";
        // ofs,输出到文件
        std::cin.tie(prevstr);
        // 恢复
        ofs.close();
        system("pause");
        return 0;
        }
    
  • 相关阅读:
    10.flask博客项目实战五之用户登录功能
    09.flask博客项目实战四之数据库
    08.flask博客项目实战三之表单
    07.flask博客项目实战二之模板使用
    06.flask博客项目实战一之项目框架搭建
    05.flask数据库
    04.flask表单
    03.flask模板
    idea 灵异事件之maven 缓存
    如何查看Spring Boot 默认的数据库连接池类型
  • 原文地址:https://www.cnblogs.com/chmod/p/15489936.html
Copyright © 2011-2022 走看看