假设我有 2 个 int 数组
int[10] A; //[1,1,1,1,1,1,1,1,1,1]
int[10] B; //[2,2,2,2,2,2,2,2,2,2]
数组C的结果应该是
int[10] C; //[3,3,3,3,3,3,3,3,3,3]
我应该如何获得结果 C 而不是使用 for 循环遍历每个 A 和 B?换句话说,是否可以通过使用GPU进行并行计算来节省计算时间?
我读过,通过使用 RenderScript,可以进行此类计算。我应该怎么做?如果有人可以指导我或将我指向引用站点,我会很高兴。
我已经读过这个但仍然感到困惑:How to pass array values to and from Android RenderScript using Allocations
是否也可以使用 OpenGl ES 来做到这一点?我在这篇文章中读到无法声明数组:How to define constant array in GLSL (OpenGL ES 2.0)?
当前解决方案:
RenderScript fragment
int32_t *A;
int32_t *B;
int32_t __attribute__((kernel)) kernelAdd(int32_t in) {
int32_t C;
C = A[in] + B[in];
return C;
}
Java 代码段:
private void intAdd3(int[] A, int[] B) {
RenderScript rs = RenderScript.create(this);
ScriptC_rsintadd intaddscript = new ScriptC_rsintadd(rs,
getResources(), R.raw.rsintadd);
mScript = intaddscript;
// Create allocation for arrays
Allocation a = Allocation.createSized(rs, Element.I32(rs), A.length);
a.copyFrom(A);
intaddscript.bind_A(a);
Allocation b = Allocation.createSized(rs, Element.I32(rs), B.length);
b.copyFrom(B);
intaddscript.bind_B(b);
Allocation array = Allocation.createSized(rs, Element.I32(rs), SIZE);
int[] array_size = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
array_size[i] = i;
}
array.copyFrom(array_size);
// create blank memory for c
int[] C = new int[SIZE];
Allocation c = Allocation.createSized(rs, Element.I32(rs), C.length);
intaddscript.forEach_kernelAdd(array, c);
c.copyTo(C);
for (int i = 0; i < SIZE; i++) {
System.out.println("intadd3" + i + ": " + C[i]);
}
}
最佳答案
假设您已经分配了数组并且它们在范围内可用:
void __attribute__((kernel)) kernelAdd(uint32_t x) {
C[x] = A[x] + B[x];
}
看看http://developer.android.com/guide/topics/renderscript/compute.html#writing-an-rs-kernel
关于java - android上的数组加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28299193/