Question

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++.

Était-ce utile?

La solution 2

This code:

#include<iostream>
#include<cmath>

using namespace std;

int main()
{
    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;
        }
    }
    cout << product;
}

takes 12.1 seconds on my 3.4GHz Athlon64 machine (using g++ 4.6.3 in 64-bit mode - it's slower in 32-bit mode, for natural reasons, since all the 64-bit operations take twice as many steps, it takes just short of twice as long). If I remove the cout << product; line, it takes 0.004s.

If I put the cout line back in and do -funroll-all-loops it takes it down to 4.5s.

I don't have a Java environment to run the Java code, but I don't see believe it would run faster than the C++ code.

Autres conseils

You compiled it without optimization. Compile with proper settings and the C++ version will run in 0 seconds, because it does nothing.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top