Run-time difference in C and C ++

I recently found this site called codechef, where you can submit solutions to problems. I posted two answers to the question, one in C and the other in C ++. Both codes are almost the same. But when the code I presented in C was executed in 4.89s, the code I sent to C ++ was disabled (more than 8 seconds). How is this possible? Where is the time going?

The question was:

Enter

Input starts with two natural numbers nk (n, k <= 107). The next n lines of input contain one positive integer ti, no more than 10 ^ 9, each.

Exit

Write a single integer to output, indicating how many integers ti are divided 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; } 
+8
c ++ c
Mar 06 '14 at 13:01
source share
1 answer

The code is actually not the same, even if it does the same

The C ++ version uses cin and threads, which are slower by default than scanf.

By default, cin / cout response time is synchronized with stdio buffers in C libraries, so you can freely mix scanf / printf calls with cin / cout operations. You can disable this with std::ios_base::sync_with_stdio(false);

Thus, the time taken will be more or less the same, I would expect

+28
Mar 06 '14 at 13:04
source share



All Articles