Difference in execution time in C and C++

前端 未结 2 1643
Happy的楠姐
Happy的楠姐 2021-01-05 06:37

I recently found this site called codechef, where you can submit solutions to problems. I had submitted two answers for a question, one in C and the other in C++. Both codes

相关标签:
2条回答
  • 2021-01-05 07:06

    The code is not really the same even though they do the same thing

    The c++ version uses cin and streams which are slower than scanf etc by default.

    By default, cin/cout waste time synchronizing themselves with the C library’s stdio buffers, so that you can freely intermix calls to scanf/printf with operations on cin/cout. You can turn this off with std::ios_base::sync_with_stdio(false);

    By doing this the time taken will more or less be similar I would expect

    0 讨论(0)
  • 2021-01-05 07:06

    I usually add these 3 lines in my code just after the main() for faster input output :

    ios_base::sync_with_stdio(false);
    
    cin.tie(NULL);
    
    cout.tie(NULL);
    

    So , Try this :

    int main()  
    {
       ios_base::sync_with_stdio(false);
       cin.tie(NULL);
       cout.tie(NULL);
       int n, k, t,num=0;
       cin>>n>>k;
       for(int i=0;i<n;i++)  {
         cin>>t;
         if(t%k==0)  num++;
       }
    
       cout<<num;
       return 0;
     } 
    
    0 讨论(0)
提交回复
热议问题