Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java faster than C [duplicate]

Today I made a simple test to compare the speed between java and c - a simple loop that makes an integer "i" increment from 0 to two billion.

I really expected c-language to be faster than java. I was surprised of the outcome:

the time it takes in seconds for java: approx. 1.8 seconds

the time it takes in seconds for c: approx. 3.6 seconds.

I DO NOT think that java is a faster language at all, but I DO NOT either understand why the loop is twice as fast as c in my simple programs?

Did I made a crucial misstake in the program? Or is the compiler of MinGW badly configurated or something?

public class Jrand {

 public static void main (String[] args) {

    long startTime = System.currentTimeMillis();
    int i; 
    for (i = 0; i < 2000000000; i++) {
        // Do nothing!
    }
    long endTime = System.currentTimeMillis();
    float totalTime = (endTime - startTime);

    System.out.println("time: " + totalTime/1000);
 }

}

THE C-PROGRAM

#include<stdio.h>
#include<stdlib.h>
#include <time.h>
int main () {

    clock_t startTime;
    startTime = clock();

    int i;
    for (i = 0; i <= 2000000000; i++) {
        // Do nothing
    }
    clock_t endTime;
    endTime = clock();

    float totalTime = endTime - startTime;
    printf("%f", totalTime/1000);

    return 0;
}
like image 250
Björn Hallström Avatar asked Sep 16 '13 17:09

Björn Hallström


People also ask

Can Java be faster than C?

C is normally faster than Java, if it is written efficiently, but it always depends on the compiler. Some compilers support optimization on the compile time, to produce more efficient code, by removing redundant code and other unnecessary artefacts.

Is Java efficient and faster than C?

Java is compiled into a lower language, then interpreted. It also has automatic garbage collection, and it's farther from machine code in the first place. Because of this C code tends to run faster than Java, but difference depends on what's being done and how well the code has been optimized.

Is Java faster than C Plus Plus?

Speed and performance Java is a favorite among developers, but because the code must first be interpreted during run-time, it's also slower. C++ is compiled to binaries, so it runs immediately and therefore faster than Java programs.

Is Java slower than C?

Java startup time is often much slower than many languages, including C, C++, Perl or Python, because many classes (and first of all classes from the platform Class libraries) must be loaded before being used.


1 Answers

Rebuild your C version with any optimization level other than -O0 (e.g. -O2) and you will find it runs in 0 seconds. So the Java version takes 1.6 seconds to do nothing, and the C version takes 0.0 seconds (really, around 0.00005 seconds) to do nothing.

like image 91
R.. GitHub STOP HELPING ICE Avatar answered Sep 18 '22 15:09

R.. GitHub STOP HELPING ICE