java和c 的运行速度,为什么我的本机C ++代码在Android上的运行速度比Java慢得多?...

I ported some portions of my Java code to C++ to speed up calculations on Android (this was a physics subroutine). What I found was that the native code runs several times slower than the Java code. I thought maybe something was wrong with the configuration of my project, or maybe with the array handling, so I put a simple loop in the HelloAndroidJni project to test raw speed difference, and got similar results.

Java Code:

@Override

protected void onCreate(Bundle savedInstanceState) {

/* ...generic boilerplate code... */

TextView tv = (TextView) findViewById(R.id.sample_text);

int loopCount = 100000;

//time the native method

long ticks = System.nanoTime();

int result = nativeTest(100000);

long nativeTime = (System.nanoTime() - ticks) / 100000;

//time the Java method

ticks = System.nanoTime();

result = javaTest(100000);

long javaTime = (System.nanoTime() - ticks) / 100000;

//present results

tv.setText("Native=" + nativeTime + "; Java=" + javaTime);

}

The loop in Java:

int javaTest(int count) {

int result = 0;

for (int i = 0; i < count; i++) {

for (int j = 0; j < 100; j++) {

result += 34432; result++;

result -= 34431; result--;

} }

return result;

}

And the C++ code:

JNIEXPORT jint JNICALL

Java_com_fringecode_helloandroidjni_MainActivity_nativeTest(

JNIEnv *env, jobject jThis, jint count) {

int result = 0;

for (int i = 0; i < count; i++) {

for (int j = 0; j < 100; j++) {

result += 34432; result++;

result -= 34431; result--;

} }

return result;

}

The rest of the project is identical to the HelloAndroidJni sample project. The result of a typical run is Native=2580 ms, Java=195 ms. What could be making the native code run so much slower than the Java?

EDIT: Incidentally, the native code runs much faster than Java on the emulator, but on my phone (LG V20 / Snapdragon 820) the native is much slower.

解决方案

Java on the fly optimization may make your loop be as fast as native. On the other hand, without APP_OPTIM=release the C++ compiler will generate debug unoptimized code.

The takeaway is that actually number crunching in Java may be quite efficient, if coded in disciplined manner. But after all, coding same efficiently in C also requires discipline.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值