C# or C - which is faster?

Status
Not open for further replies.

sarabjit

Solid State Member
Messages
11
I ran the following (same) 2 small programs in C#.NET and then in C (Bloodshed Dev C/C++). The latter took more time than the former (4.7s vs 3.8s) - I thought this was counter-intuitive, and that a code written in C should run faster... Any Ideas?

C#:
---
public static void Main()
{

// variables
int i, i1=0;
int[] ar=new int[1000];
long l1, l2;

// first for loop - 1Billion iterations
for (i=0;i<1000000000;i++)
{
ar[i1]=i;
i1++;
if (i1==1000) i1=0;
}

// measure time
l1=DateTime.Now.Ticks;
i1=0;

// second for loop - 1Billion iterations
for (i=0;i<1000000000;i++)
{
ar[i1]=i;
i1++;
if (i1==1000) i1=0;
}

// measure time
l2=DateTime.Now.Ticks;

// print results
Console.WriteLine("Time befre: {0}",l1);
Console.WriteLine("Time after: {0}",l2);
l2-=l1;
Console.WriteLine("Time taken in seconds: {0}",(double)l2/10000000);
Console.ReadLine();
}

C:
--
#include <time.h>

main() {

// variables
int i, i1=0;
int ar[1000];
clock_t c1, c2;

// first for loop - 1Billion iterations
for (i=0;i<1000000000;i++) {
ar[i1]=i;
i1++;
if (i1==1000) i1=0;
}

// measure time
c1=clock();
i1=0;

// second for loop - 1Billion iterations
for (i=0;i<1000000000;i++) {
ar[i1]=i;
i1++;
if (i1==1000) i1=0;
}

// measure time
c2=clock();

// print results
printf("Time befre: %d\n",c1);
printf("Time after: %d\n",c2);
c2-=c1;
printf("Time taken in seconds: %f",(float)c2/1000);
getchar();
}
 
It could be dependent on the compiler you used.

For large loops like that, it's very easy for newer compilers to take advantage of cache optimizations. I've never used Dev before, but I know the latest gcc version does this with the -o2 flag.
 
I have written a routine in .NET which uses repeated interations of integer arrays approximately 1000x1000 elements... The total time taken in .NET is around 2.5s.. I was hoping I'd be able to improve the time using C, and compiling the method into a dll.. Any suggestions?
 
You might have better luck posting this in the Programming section.

In specific, I'd look for Iron_Cross. He's insane with anything programming.
 
Status
Not open for further replies.
Back
Top Bottom