zoukankan      html  css  js  c++  java
  • 8-cin cout PK scanf printf(速度快慢问题对比)

    我们在c++ 中使用cin cout很方便但速度很慢,导致有些题目用cin就超时而用scanf则就ac了,那到底改用谁?

    cin慢是有原因的,其实默认的时候,cin与stdin总是保持同步的,也就是说这两种方法可以混用,而不必担心文件指针混乱,同时cout和stdout也一样,两者混用不会输出顺序错乱。正因为这个兼容性的特性,导致cin有许多额外的开销,如何禁用这个特性呢?只需一个语句std::ios::sync_with_stdio(false);,这样就可以取消cin于stdin的同步了。

    我写了两段代码测试了cout 和printf的运行速度:

        #include<windows.h>   
        #include<iostream>
        using namespace std;  
        int main()  
        {  
            ios::sync_with_stdio(false);  //取消cin 与 scanf()同步  
            double a = 0, b = 0;
            
            a = GetTickCount();
            for(int i = 1; i <= 3000; i++)
                cout << i;
    //            printf("%d", i);
            cout << endl;
            a = GetTickCount() - a;   
            cout << "time: " << a;  
            return 0;  
     } 

        #include<windows.h>   
        #include<stdio.h>
        int main()  
        {  
    //        ios::sync_with_stdio(false);  //取消cin 与 scanf()同步  
            double a = 0, b = 0;
            
            a = GetTickCount();
            for(int i = 1; i <= 3000; i++)
                printf("%d", i);
            a = GetTickCount() - a;   
             printf(" time: %lf ", a);
            return 0;  
        } 

    未使用ios::sync_with_stdio(false)

    使用ios::sync_with_stdio(false)

    用scanf:

  • 相关阅读:
    第五节、矩阵分解之LU分解
    第四节、逆矩阵与转置矩阵
    第三节、矩阵乘法
    第二节、矩阵消元(高斯消元)
    重学线代——声明篇
    第一节、方程组的几何解释
    String类
    Mycat的安装及配置
    使用InfluxDB、cAdvisor、Grafana监控服务器性能
    Rancher的使用
  • 原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/7309287.html
Copyright © 2011-2022 走看看