计算二维数组的总和很慢

时间:2019-09-12 19:14:20

标签: android c arrays renderscript

我正在使用RenderScript构建一个Android应用程序。我想创建一个二维数组,其中包含从原点到(x,y)的矩形中所有整数的总和。

here所述,RenderScript是C99派生的语言。框架将为每个像素调用带有-vm /yourJvmPath/jdk-12.0.1.jdk/bin/java 关键字的任何函数一次。不保证将以什么顺序调用它。从Java / Kotlin中-vm /Users/SomeUser/jdk-12.0.1.jdk/bin/java -startup ../Eclipse/plugins/org.eclipse.equinox.launcher_1.5.400.v20190515-0925.jar --launcher.library ../Eclipse/plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.1000.v20190125-2016 通过为其分配一块内存来调用。每个项目都由返回值进行相应设置。

例如,

RS_KERNEL

对于较小的数组,这是可行的,但是当数组与屏幕一样大(1080x2280)时,我编写的函数会花费很多时间。

generateGridPixelCount

但是,如果 Input Output ----------------- | 0 | 0 | 0 | 0 | ------------- ----------------- | 1 | 1 | 1 | | 0 | 1 | 2 | 3 | ------------- ----------------- | 0 | 1 | 1 | | 0 | 1 | 3 | 5 | ------------- ----------------- | 1 | 1 | 1 | | 0 | 2 | 5 | 8 | ------------- ----------------- 被删除或if语句被删除,则它几乎立即完成。是它变慢的时候结合在一起。

上一个static bool shouldCheckPixel(uint x, uint y) { return (x + y) % (width / stepSize) == 0 || (x - y) % (width / stepSize) == 0; } int RS_KERNEL generateGridPixelCount(uint x, uint y) { int pixelCount = 0; for (int dx = 0; dx < x; dx++) { for (int dy = 0; dy < y; dy++) { if (shouldCheckPixel(dx, dy)) { pixelCount++; } } } return pixelCount; } 函数在输出上循环。这可以逆转:

pixelCount++;

计算此数组的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

Eric Postpischil将我推向正确的方向;以下代码段是我现在使用的代码。

科特琳:

script.forEach_generateShouldCheckPixelLookup(shouldCheckPixelLookup)
script.invoke_generateShouldCheckPixelSum()

RenderScript:

int RS_KERNEL generateShouldCheckPixelLookup(uint x, uint y) {
    if (shouldCheckPixel(x, y)) {
        return 1;
    } else {
        return 0;
    }
}

void generateShouldCheckPixelSum() {
    for (int y = 1; y < height + 1; y++) {
        for (int x = 1; x < width + 1; x++) {
            int top     = rsGetElementAt_int(shouldCheckPixelSum, x,     y - 1);
            int left    = rsGetElementAt_int(shouldCheckPixelSum, x - 1, y);
            int topLeft = rsGetElementAt_int(shouldCheckPixelSum, x - 1, y - 1);

            int current = rsGetElementAt_int(shouldCheckPixelLookup, x, y);
            int value = top + left - topLeft + current;

            rsSetElementAt_int(shouldCheckPixelSum, value, x, y);
        }
    }
}

generateShouldCheckPixelLookup每个像素调用一次,并将结果存储在shouldCheckPixelLookup中。然后generateShouldCheckPixelSum被调用一次并运行一次。

我的想法是,由于RenderScript尝试并行运行每个像素的每个调用,因此它总是比运行单个函数调用更快。但是,generateShouldCheckPixelSum与我最初提出的问题中最慢的generateGridPixelCount一样快。

相关问题