- 论坛徽章:
- 0
|
1. 同样的xun环,用for和while在jni层调用,为什么会相差这么大?
打印结果:
V/Hello ( 2385): func:Java_com_example_hellojni_HelloJni_stringFromJNI,line:72, next test_for
V/Hello ( 2385): func:test_for,line:42, only 4 loops cost 942.406 ms
V/Hello ( 2385): func:Java_com_example_hellojni_HelloJni_stringFromJNI,line:74, next test_while
V/Hello ( 2385): func:test_while,line:67, only 4 loops cost 0.00219727 ms
可以看出:
for 942.406 ms
while 0.00219727 ms
为什么会相差这么大?
以下代码复制到 android-ndk/sample/hello-jni/jni/hello-jni.c 就可以直接编译,运行。
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <string.h>
#include <jni.h>
#include <android/log.h>
#include <sys/time.h>
#define TAG "Hello"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
#define LOGC(x, ...) LOGV("func:%s,line:%d, "x, __FUNCTION__,__LINE__, ##__VA_ARGS__)
static double now_ms(void)
{
struct timeval res;
gettimeofday(&res, NULL);
return 1000.0*res.tv_sec + (double)res.tv_usec/1e3;
}
int test_for(void)
{
double iTimer1, iTimer2;
int xxx, yyy, zzz, uuu, vvv;
iTimer1 = now_ms();
for(yyy=0; yyy<10; yyy++)
for(xxx=0; xxx<1000; xxx++)
for(zzz=0; zzz<100; zzz++)
for(uuu=0; uuu<100; uuu++)
;
iTimer2 = now_ms();
LOGC("only 4 loops cost %g ms",iTimer2 - iTimer1);
}
int test_while(void)
{
double iTimer1, iTimer2;
int xxx, yyy, zzz, uuu, vvv;
iTimer1 = now_ms();
while(yyy<10)
{
while(xxx<1000)
{
while(zzz<100)
{
while(uuu<100)
{
uuu++;
}
zzz++;
}
xxx++;
}
yyy++;
}
iTimer2 = now_ms();
LOGC("only 4 loops cost %g ms",iTimer2 - iTimer1);
}
jstring Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz )
{
LOGC("next test_for");
test_for();
LOGC("next test_while");
test_while();
return (*env)->NewStringUTF(env, "Hello from JNI !");
}
|
|