问题
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:
Input
The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 10^9, each.
Output
Write a single integer to output, denoting how many integers ti are divisible by k.
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;
}
回答1:
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
回答2:
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;
}
来源:https://stackoverflow.com/questions/22225333/difference-in-execution-time-in-c-and-c