我最近开始尝试学习OpenCl,并试图将以下代码转换为高效的OpenCl内核:
for(int i = 0; i < VECTOR_SIZE; i++)
{
for(int j = 0; j < 100; j++)
{
C[i] = sqrt(A[i] + sqrt(A[i] * B[i])) * sqrt(A[i] + sqrt(A[i] * B[i]));
}
}
这是我到目前为止使用不同教程得出的结果。我的问题是,我能不能摆脱内核中的外循环。你会说这是上面c++代码的一个很好的实现,并且没有进一步的事情可以做得更有效率或接近一个openCL程序应该是什么样的吗?
而且,到目前为止我读过的所有教程都是用const char *编写内核的。这背后的原因是什么?这是OPenCL内核编写的唯一方式吗?或者通常我们在其他文件中编写它们,然后将其包含在我们的常规代码或其他东西中。
感谢 const char *RandomComputation =
"__kernel n"
"void RandomComputation( "
" __global float *A, n"
" __global float *B, n"
" __global float *C) n"
"{ n"
" //Get the index of the work-item n"
" int index = get_global_id(0); n"
" for (int j = 0; j < 100 ; j++) n"
" { n"
" C[index] = sqrt(A[index] + sqrt(A[index] * B[index])) * sqrt(A[index] + sqrt(A[index] * B[index])); n"
"} n"
"} n";
当你想在OpenCL内核中使用嵌套循环时,使用像这个例子一样的二维矩阵乘法。
__kernel void matrixMul(__global float* C,
__global float* A,
__global float* B,
int wA, int wB)
{
int tx = get_global_id(0);
int ty = get_global_id(1);
float value = 0;
for (int k = 0; k < wA; ++k)
{
float elementA = A[ty * wA + k];
float elementB = B[k * wB + tx];
value += elementA * elementB;
}
C[ty * wA + tx] = value;
}
你需要这里的完整解释吗