CPU 运行速度比 GPU 快(OpenCL 代码)

标签 c linux parallel-processing opencl gpgpu

我在 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 更快吗?或者,我的代码/实现有什么问题吗? 请解释此行为。

最佳答案

clEnqueueTask() 所以基本上,您在 GPU 中运行 1 个“线程”(工作项)。 GPU 永远不会在单线程性能上击败 CPU。

您需要转换您的代码,这样您就可以将每个素数计算分配到一个线程,然后运行 ​​5000 多个工作项(最好是数百万)。然后,GPU 将击败 CPU,因为它可以并行运行所有任务,而 CPU 不能。

为了使用多个工作项,请使用 clEnqueueNDRangeKernel() 调用您的内核

关于CPU 运行速度比 GPU 快(OpenCL 代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31242023/

相关文章:

c - 在所有过程完成但输出奇怪后使用等待等待

c# - 如果作为单独的任务启动,有没有办法取消 Parallel.ForEach 循环

c++ - 指令级并行探索

c++ - Linux 上的 NPAPI (npruntime)

linux - 用于打开终端并 cd 到变量目录的 Bash 脚本

javascript并行加载

C typedef 指向 func 的指针,参数指针指向结构

c - C 语言的 ECDH 库?

c - C中实现结构的动态分配

Linux Bash 文件名自动编号而不删除前导零