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:

  • 相关阅读:
    Intellijidea建javaWeb以及Servlet简单实现
    PHP关于文件与文件夹(1) 写入文件 文件权限 三、锁定文件
    mysql 时间戳格式化函数from_unixtime使用说明
    Ansible 2.0公布
    如何获取板子上独有的ID号EXYNOS4412/Imx6ul【转】
    2.7 xargs和exec详解【转】
    __setup 在内核中的作用【转】
    Linux __setup解析【转】
    c语言中 %p的含义【转】
    函数 devm_kzalloc()【转】
  • 原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/7309287.html
Copyright © 2011-2022 走看看