Android, Java faster than C++ [Solved]
-
hi,
I have an Android application that simply calculate the first N prime numbers in both way: C++ and Java (using JNI).
The C++ code is:... long m_startNum=0; long m_endNum=100000; ... void Engine::primeNumbers() { int tot_prime=0; int count=0; for( long i=m_startNum;i<=m_endNum;i++) { for( long j=2;j<=sqrt(i);j++) { if(i%j==0) count++; } if(count==0 && i!=1) { tot_prime++; count=0; } count=0; } emit ended(); qDebug() << "TOT TROVATI: " << tot_prime; emit newPrimeNumber(tot_prime); }
The Java version is:
void Engine::primeNumbersJava() { jint tot = QAndroidJniObject::callStaticMethod<jint>( "com/test/calc_test_java/PrimeNumbers", "primeNumbers"); qDebug() << "TOT TROVATI: " << tot; emit newPrimeNumber(tot); emit ended(); }
and my Java class:
package com.test.calc_test_java; public class PrimeNumbers { static long m_startNum = 0; static long m_endNum = 100000; public static int primeNumbers() { System.out.println("inizio primeNumbers"); int prime_found=0; int count=0; for(long i=m_startNum;i<=m_endNum;i++) { for(long j=2;j<=Math.sqrt(i);j++) { if(i%j==0) count++; } if(count==0 && i!=1) { count=0; prime_found++; } count=0; } System.out.println("fine primeNumbers"); return prime_found; } }
The strange thing is that when I execute on a tablet, the C++ version takes 4 secs to end while Java version takes only 2 secs.
I didn't expect that result...What do you think about?
Luca
-
I don't see any code measuring time. Have you actually checked it? Running Java and C++ have different runtimes spinning up and lots of other overhead - loading libraries and such. It doesn't mean that particular function runs faster or slower.
-
@Chris-Kawa
Yes, I checked time by using QElapsedTimer on the calling method of primeNumbersJava and primeNumbers.
As you write, I suppose the reason is related to library loading or something else.
But I grant you Java is very faster in my specific methods primeNumbersJava and primeNumbers... -
This post is deleted! -
Looking on the compiling output I saw that QtCreator is using "-O2" optimization flag.
I tried with -O3 by putting the following lines on .pro:
QMAKE_CXXFLAGS_RELEASE -= -O QMAKE_CXXFLAGS_RELEASE -= -O1 QMAKE_CXXFLAGS_RELEASE -= -O2 QMAKE_CXXFLAGS_RELEASE *= -O3
And now the C++ version on primeNumbers takes only 620 msec while Java version takes 2 sec .
That's what I expect!! ;-)