我将我的一些 Java 代码移植到 C++ 上,以加快在 Android 上的计算速度(这是一个物理子程序)。但我发现本地代码运行的速度比 Java 代码慢几倍。我想也许是项目配置出了问题,或者数组处理有误,所以我在 HelloAndroidJni 项目中放了一个简单的循环来测试原始速度差异,并得到类似的结果。
Java 代码:
@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;
}
以下是C++代码:
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;
}
项目的其余部分与HelloAndroidJni示例项目相同。典型运行结果为Native=2580毫秒,Java=195毫秒。是什么导致本地代码比Java运行得慢那么多呢?
编辑:顺便说一句,在模拟器上,本地代码比Java运行得快得多,但在我的手机(LG V20 / Snapdragon 820)上,本地代码要慢得多。
std::string
?难道你不能直接使用return env->NewStringUTF("Hello from C++");
而不浪费额外的动态内存分配和释放吗? - Useless