2014-01-10 98 views
1

我正在编写一个C++代码,用于比较使用CPU和GPU版本的openCv的morphologyEx方法的性能。这里是我的代码:gpu :: morphologyEx比CPU更慢吗?

#include <opencv2/opencv.hpp> 
#include <opencv2/gpu/gpu.hpp> 
#include <sys/time.h>  
#include <ctime> 
using namespace cv; 
using namespace std; 


double start_timer() 
{ 
    double start_time = (double) getTickCount(); 
    return start_time; 
} 

double end_timer(double start_time,int num_tests) 
{ 
    double time = (1000 * ((double) getTickCount() - start_time)/ getTickFrequency()); 
    cout << "Average time of " << num_tests << " frames is: " << time/num_tests << " ms" << endl; 
    return time; 
} 


int main() 
{ 
    Mat cpuSrc; 
    cv::gpu::GpuMat src_gpu, dst_gpu; 
    Mat dst; 
    Mat element; 
    int element_shape = MORPH_RECT; 
    element = getStructuringElement(element_shape, Size(10, 10), Point(-1, -1)); 
    cpuSrc = imread("images.jpeg",CV_LOAD_IMAGE_ANYDEPTH); 

    if (!cpuSrc.data) 
    { 
     cerr << "Cannot read the data" << endl; 
     return -1; 
    } 


    cout << "Starting calculating time for CPU ....." << endl; 
    double start_time = start_timer(); 
    int d = 0; 
    while(d<100) 
    { 
     cv::morphologyEx(cpuSrc, dst, CV_MOP_OPEN, element,Point(-1,-1),1); 
    } 

    double total_time_cpu = end_timer(start_time,d); 



//-------------------------------------------------------------- 
    cout << "Starting calculating time for GPU ....." << endl; 
    d = 0; 
    cv::gpu::GpuMat buf1, buf2; 
    gpu::Stream stream; 
    double start_time_1 = start_timer(); 

    while(d<100) 
    { 
     stream.enqueueUpload(cpuSrc, src_gpu); 
     cv::gpu::morphologyEx(src_gpu,dst_gpu,CV_MOP_OPEN,element, 
        buf1,buf2,Point(-1,-1),1,stream); 
     stream.enqueueDownload(dst_gpu, dst); 

    } 
    stream.waitForCompletion(); 
    double total_time_gpu = end_timer(start_time_1,d); 

    cout << "Gain is: " << total_time_cpu/total_time_gpu << endl; 
    return 0; 
} 

我使用的是循环的,如果我模拟包含100帧的视频。我使用NVIDIA Corporation GF110 [GeForce GTX 570]和Intel Corporation Xeon E5/Core i7 DMI2。此外,我测试了上传和下载的时间,它在第一帧非常大,但之后可以忽略大约上传它是每帧0.02ms,下载是0.1ms,主要时间消耗是与morphologyEx操作。


这个模拟的时间,结果如下:

为CPU形态版本,100帧的 平均时间是:: 0.027349毫秒和用于GPU的版本是:: 18.0128毫秒

请你帮我弄清楚可能是什么原因导致这种意外的表现?

非常感谢您提前。

+1

你能给出图像大小,处理器的确切型号和你的系统配置(包括操作系统细节)..? – scap3y

+1

任何GPU函数的第一次调用包括CUDA上下文初始化,可能需要很长时间。所以第一次测量是异常的,这会影响总的平均时间。 – jet47

+0

@ scap3y图片尺寸540 * 960。 Ubuntu 12.04 LTS 64位。英特尔公司Xeon E5 /酷睿i7 DMI2(rev 07) –

回答

1

在初始化你应该叫:

cv::gpu::setDevice(0); 

这将加快初始化。

+0

即使加入了这个初始化后,结果仍然完全一样? :( –