Same code, but twice slower

So, here is this code. I compiled it with both C(tcc) and C++(VS2012), and the result each program printed was quite weird. The average time of C++ was around 0.2 and C had 0.4. How is that possible. Isn't C supposed to be faster?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <time.h>
#include <conio.h>


double st,end;

int main()
{
	double val = 0;
	for(int j = 0;j < 10; j++)
	{
		st=clock();
		long a1 = 0, a2 = 0;


		for(int k = 0; k< 1000000;k++)
		{
			a1++;
			for(int i = 0; i < 100; i++)
			{
				a2+=a1;
			}
		}

		end=clock();
		val+=(end-st)/CLK_TCK;
		printf("TIME TAKEN=%f SEC\n",(end-st)/CLK_TCK);
	}


	std::cout << "Average time " <<  val/10.0;
	_getch();
	return 0;
}
You compiled the same code with different compilers and got different results?

Go figure.

Isn't C supposed to be faster?

No.

http://stackoverflow.com/questions/6955114/is-c-notably-faster-than-c
I dropped conio.h and _getch(), added #include <cstdio>, and replaced CLK_TCK with double(CLOCKS_PER_SEC) to get this to compile.

The result is zero in every compiler I tried: clang++ 3.2, intel 13.0, gcc 4.7.2, as expected, since the code you're measuring does nothing and is eliminated by compilers.

Why did your compilers print something greater than zero, did you disable optimizations?
Execution time depends a little on compiler used and a lot on methods used in code. A lot of simpler methods used means faster code. Small lines of code but with hugely dense methods means slower execution time.

Look up RISC vs CISC compilers
Topic archived. No new replies allowed.