i wonder why is this happening all the time…!!
I wrote two programs one in c and the other in c++.. Both performs the same action. i.e prints numbers from 1 to 2000000. Also i am setting the timer at the begtinning of execution.. and after printing all the numbers time elapsed is also printed..
The time elapsed for a c++ program is always greater than for a c program.
i feel the difference in time is significant. I am curious to know what is the cause for this..????..
Here are the two programs
//iotest.c
#include<stdio.h>
#include<time.h>
clock_t start=clock();
int main()
{
for(int i=0;i<2000000;i++)
printf("%d\n",i);
printf("Time Elapsed: %f\n",((double)clock()-start)/CLOCKS_PER_SEC);
return 0;
}
//iotest.cpp
#include<iostream>
#include<time.h>
using namespace std;
clock_t start=clock();
int main()
{
for(int i=0;i<2000000;i++)
cout<<i<<endl;
cout<<"Time elapsed "<<((double)clock()-start)/CLOCKS_PER_SEC<<endl;
return 0;
}
// ver C++ 4.3.2
Compiling c program by issuing the command
g++ iotest.c
Execution gives
1
.
.
2000000
Time Elapsed: 5.410000(Not always same..)
Executing the second program
1
.
.
2000000
Time elapsed: 5.81(Not always same..)
The difference between the two programs is that the C++ version uses
endl, which not only inserts a newline but flushes the buffer. The slow part of doing any output is flushing the buffer.Both programs would probably be about the same speed if you made your C++ program use
The following two programs achieve a similar execution time:
C-program (
a.c):Compile with:
gcc -O3 -std=c99 a.cC++-program (
b.cpp):Compile with
g++ -O3 b.cpp