本文介绍了C和C ++中执行时间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现这个网站叫codechef,你可以提交问题的解决方案。
我为一个问题提交了两个答案,一个在C中,另一个在C ++中。两个代码几乎相同。但是当我在C提交的代码在4.89s执行时,我在C ++提交的代码超时(超过8秒)。这怎么可能?



问题是:





 示例

输入:
7 3
1
51
966369
7
9
999996
11

输出:
4



C:



 #include< stdio.h> 

int main(){

int n,k,t;
scanf(%d%d,& n,& k);
int i,num = 0;
for(i = 0; i scanf(%d,& t);
if(t%k == 0)num ++;
}

printf(%d,num);

return 0;
}



我在C ++中的代码:



 #include< iostream> 

using namespace std;

int main(){

int n,k,t,num = 0;
cin>>> n>> k;
for(int i = 0; i cin>> t;
if(t%k == 0)num ++;
}

cout<< num;
return 0;
}


解决方案
























b

默认情况下,cin / cout会浪费时间与C库的stdio缓冲区同步,以便您可以自由地混合使用cin / cout操作对scanf / printf的调用。您可以使用 std :: ios_base :: sync_with_stdio(false);



关闭此功能。采取将或多或少相似我期望


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 are almost the same. But when the code I submitted in C was executed in 4.89s, the code I submitted in C++ was timed out (more than 8 seconds). How is this possible? Where does the time go?

The question was:

Example

Input:
7 3
1
51
966369
7
9
999996
11

Output:
4

My code in C:

 #include<stdio.h>

 int main()  {

   int n,k,t;
   scanf("%d %d",&n,&k);
   int i,num=0;
   for(i=0;i<n;i++)  {
     scanf("%d",&t);
     if(t%k==0)  num++;
   }

   printf("%d",num);

   return 0;
 }

My Code in C++:

 #include<iostream>

 using namespace std;

 int main()  {

   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;
 }
解决方案

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

这篇关于C和C ++中执行时间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 12:01
查看更多