我想让我的Android Studio代码更快,所以我将一些Java代码翻译成本机C.令人惊讶的是,用c编写的函数执行速度比java函数快三倍。此外,我已经应用了ndk构建优化,但没有改变任何东西。我的代码:
1)Java函数:
private int[] convolve(short signal[], short kernel[]) {
int ret[] = new int[signal.length + kernel.length - 1];
for (int n = 0; n < ret.length; n++){
ret[n] = 0;
int kmin = (n >= kernel.length - 1) ? n - (kernel.length - 1) : 0;
int kmax = (n < signal.length - 1) ? n : signal.length - 1;
for (int k = kmin; k <= kmax; k++) {
ret[n] += signal[k] * kernel[n - k];
}
}
return ret;
}
2)C函数:
int convolve_max(int16_t Signal[/* SignalLen */], int32_t SignalLen,
int16_t Kernel[/* KernelLen */], int32_t KernelLen)
{
int32_t n;
double Result;
double MaxVal = 0;
int32_t MaxInd = 0;
double abs_sum = 0;
for (n = 0; n < SignalLen + KernelLen - 1; n++) {
int32_t kmin, kmax, k;
Result = 0;
kmin = (n >= KernelLen - 1) ? n - (KernelLen - 1) : 0;
kmax = (n < SignalLen - 1) ? n : SignalLen - 1;
for (k = kmin; k <= kmax; k++) {
Result += Signal[k] * Kernel[n - k];
}
Result = abs(Result);
abs_sum += Result;
if (Result > MaxVal) {
MaxVal = Result;
MaxInd = n;
}
}
double trs = abs_sum / 200;
int offset = 0;
if (MaxVal > trs) {
offset = MaxInd - 10 * 512;
}
else {
offset = 51;
}
if (abs(offset) < 25) {
return 1;
}
return 0;
}
我知道它们并不完全相同,但最重要的是嵌套循环,这是相同的。
另外,我的Gradle ndk版本的外观:
externalNativeBuild {
ndkBuild {
cppFlags "-std=c++11"
arguments "APP_STL=gnustl_static","NDK_TOOLCHAIN_VERSION=4.9","APP_OPTIM=release","NDKDEBUG=0", "V=1"
abiFilters "armeabi"
}
}`
我犯了一些错误,或者jni有问题吗?