Showing posts with label Is Java Slower Than C?. Show all posts
Showing posts with label Is Java Slower Than C?. Show all posts

Saturday, 10 January 2015

Is Java Slower Than C?

I have seen this suggested before so I decided to check it out on my own PC. I built it myself 11 years ago and it has a Celeron processor. Nothing else was running on the machine at the time. I wrote the C program below and used it to count to 1 billion. It took 12 seconds:

andrew@UBUNTU:~/Java$ cat prog79.c
#include <stdio.h>
void main(void)
{
double x=0;
long a,b;
for (a=1;a<=10000;a++)
  {
  for (b=1;b<=100000;b++)
    {
    x++;
    }
  }
printf("x = %e ", x);
}
andrew@UBUNTU:~/Java$ cc -o prog79.o prog79.c
andrew@UBUNTU:~/Java$ date;./prog79.o;date
Sat Jan 10 18:31:43 GMT 2015
x = 1.000000e+09 Sat Jan 10 18:31:55 GMT 2015
andrew@UBUNTU:~/Java$


I wrote the same program in Java and it only took 3 seconds so, on the basis of this test at least, Java is not slower than C: 

andrew@UBUNTU:~/Java$ cat prog79.java
public class prog79
{
public static void main (String args[])
  {
  double x=0;
  long a,b;
  for (a=1;a<=10000;a++)
    {
    for (b=1;b<=100000;b++)
      {
      x++;
      }
    }
  System.out.println("x = " + x);
  }
}
andrew@UBUNTU:~/Java$ javac prog79.java
andrew@UBUNTU:~/Java$ date;java prog79;date
Sat Jan 10 18:39:00 GMT 2015
x = 1.0E9
Sat Jan 10 18:39:03 GMT 2015
andrew@UBUNTU:~/Java$