Java is faster than C

Today I did a simple test to compare the speed between java and c - a simple cycle that increases the number of "i" from 0 to two billion.

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

time spent in seconds for java: approx. 1.8 seconds

time required in seconds for c: approx. 3.6 seconds.

I DO NOT think Java is a faster language in general, but I DO NOT understand why the loop is twice as fast as c in my simple programs?

Did I make a key mistake in the program? Or is the MinGW compiler badly configured or something like that?

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); } } 

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; } 
+6
source share
3 answers

Restore your version of C with any optimization level other than -O0 (e.g. -O2 ), and you will find that it works in 0 seconds. Thus, it takes 1.6 seconds for the Java version to do nothing, and version C takes 0.0 seconds (indeed, about 0.00005 seconds) to do nothing.

+21
source

Java is more aggressive in eliminating code that does nothing. It is less likely that the developer knows what they are doing. You do not synchronize the loop, but how long does it take java to detect and fix the loop.

In short, Java often doesn’t do anything useful faster.

You may also find that if you optimize C code and delete debugging information, it will do the same, most likely shorter.

+10
source

If you want to compare this, instead of doing nothing, try something useful, for example, calculate something at each iteration. E.g. count the loops in some other variable and make sure you use it at the end (by printing it, for example) so that it is not optimized.

Alternative simple tests can access the array linearly (read only), copy elements from one array to another (read + write), or perform some data operations. Some of these cases may be interesting, as they open up some very simple compiler optimizations that you can later see in the binary / byte encoder of the result, such as loop sweep, register allocation, and possibly even more complicated things like vectorization or code movement. Java on another can use some more unpleasant tricks, such as jitting (dynamically recompile on the fly)

The scope of compiler optimization is huge, you just came across the simplest: eliminating useless code :)

+1
source

Source: https://habr.com/ru/post/953941/


All Articles