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?
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
#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;
}
#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;
}
To find the execution time of a C program, we will use clock() function of time. h header file. clock() function returns the number of clock ticks elapsed since the program started.
To calculate time taken by a process, we can use clock() function which is available time.
Execution FlowThe preprocessor generates an expanded source code. 2) Expanded source code is sent to compiler which compiles the code and converts it into assembly code. 3) The assembly code is sent to assembler which assembles the code and converts it into object code. Now a simple. obj file is generated.
The time() function is defined in time. h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With