【发布时间】:2015-09-23 08:58:45
【问题描述】:
我在 OpenCL 中编写了一个代码来查找前 5000 个素数。这是代码:
__kernel void dataParallel(__global int* A)
{
A[0]=2;
A[1]=3;
A[2]=5;
int pnp;//pnp=probable next prime
int pprime;//previous prime
int i,j;
for(i=3;i<5000;i++)
{
j=0;
pprime=A[i-1];
pnp=pprime+2;
while((j<i) && A[j]<=sqrt((float)pnp))
{
if(pnp%A[j]==0)
{
pnp+=2;
j=0;
}
j++;
}
A[i]=pnp;
}
}
然后我使用 OpenCL 分析发现了这个内核代码的执行时间。代码如下:
cl_event event;//link an event when launch a kernel
ret=clEnqueueTask(cmdqueue,kernel,0, NULL, &event);
clWaitForEvents(1, &event);//make sure kernel has finished
clFinish(cmdqueue);//make sure all enqueued tasks finished
//get the profiling data and calculate the kernel execution time
cl_ulong time_start, time_end;
double total_time;
clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, NULL);
clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, NULL);
//total_time = (cl_double)(time_end - time_start)*(cl_double)(1e-06);
printf("OpenCl Execution time is: %10.5f[ms] \n",(time_end - time_start)/1000000.0);
我在各种设备上运行了这些代码,这就是我得到的结果:
Platform:Intel(R) OpenCL
Device:Intel(R) Xeon(R) CPU X5660 @ 2.80GHz
OpenCl Execution time is: 3.54796[ms]
Platform:AMD Accelerated Parallel Processing
Device:Pitcairn (AMD FirePro W7000 GPU)
OpenCl Execution time is: 194.18133[ms]
Platform:AMD Accelerated Parallel Processing
Device:Intel(R) Xeon(R) CPU X5660 @ 2.80GHz
OpenCl Execution time is: 3.58488[ms]
Platform:NVIDIA CUDA
Device:Tesla C2075
OpenCl Execution time is: 125.26886[ms]
但 GPU 不应该比 CPU 更快吗?或者,我的代码/实现有什么问题吗? 请解释这种行为。
【问题讨论】:
-
我认为 GPU 应该完成他们的工作:处理图形化的东西(例如大量的浮点计算)以放弃主 CPU 的工作。您编写的简单代码在更快的 CPU 上运行速度更快。
-
GPU 只有在你能够获得大量并行性的情况下才会更快,即在大量内核上运行大量线程。对于单个执行线程,GPU 将是浪费时间。
-
请阅读Why are we still using CPUs instead of GPUs?。对于所有类型的问题,GPU 并不比 CPU 快。
-
每当您尝试使用 GPU 时。首先考虑如何并行化 dara 计算。如果您不能并行化算术运算。仅在 CPU 上工作
标签: c linux parallel-processing opencl gpgpu