I wrote some code both in C++ and in Java to see which will run faster.
All this code does is it basically increments two variables and then multiplies them. As expected, C++ was slightly faster than Java.
Everything was fine until I changed the data types from int to long (long long in C++). Then C++ took a huge amount of time to execute this code, while there was little increase in execution time for Java.
Does anyone know why it takes so long for C++ to perform calculations on long, compared to Java?
C++ code *(~53 seconds, same result with __int64)* :
long long limit = 2e9;
long long loopLimitI = sqrt(limit);
long long product = 0;
for(long long i = 2; i < loopLimitI; i++){
long long loopLimitJ = limit / i;
for(long long j = 2; j < loopLimitJ; j++){
product = i * j;
}
}
Java code (~11 seconds) :
long limit = (long) 2e9;
long loopLimitI = (long) Math.sqrt(limit);
long product = 0;
for(long i = 2; i < loopLimitI; i++){
long loopLimitJ = limit / i;
for(long j = 2; j < loopLimitJ; j++){
product = i * j;
}
}
EDIT: My OS: Windows 8 (x64). Optimization settings - /O2
Both are running the code, the value of product at the end is 1999923120. Both for C++ and Java
Okay, I just tried creating an array and saving all the results of i * j multiplication (to make sure it is running). I am still getting a huge time for C++, compared with Java.
Any idea why is that happening to me?
SOLUTION:
'Platform' in MS Visual Studio is automatically set to x32. You just have to change it to 'x64'. Sorry for a rather confusing question, I am new to VS and C++.