------------只要够努力,人生最坏的结局不过是大器晚成!!!

我们在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("\n time: %lf\n", a);
        return 0;  
    } 

未使用ios::sync_with_stdio(false)

使用ios::sync_with_stdio(false)

用scanf:

posted on 2018-01-11 19:58  ystraw  阅读(537)  评论(0编辑  收藏  举报

不经一番切孤寒,怎得梅花扑鼻香