为什么openmp工作得不快?

时间:2017-11-24 09:53:13

标签: opencv openmp

我使用openmp将图像从RGB转换为灰度。但是openmp并不比正常情况快,我想知道为什么?为什么单线程比多线程更快?如何加快速度?

这是代码:

#include <iostream>
#include <omp.h>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main() {
    Mat image = imread("../family.jpg");
    Mat gray(image.rows, image.cols, CV_8UC1);

    time_t start, stop;
    start = clock();

    for (int i = 0; i < image.rows; i++)
        for (int j = 0; j < image.cols; j++) {
            gray.at<uchar>(i,j) = image.at<cv::Vec3b>(i,j)[0]*0.114
                    + image.at<cv::Vec3b>(i,j)[1]*0.587
                    + image.at<cv::Vec3b>(i,j)[2]*0.299;
        }
    stop = clock() - start;
    cout << "time: " << stop * 1.0 / CLOCKS_PER_SEC << endl;

    start = clock();


    omp_set_num_threads(4);
#pragma omp parallel
    {

#pragma omp for
        for (int i = 0; i < image.rows; i++)
            for (int j = 0; j < image.cols; j++) {
                gray.at<uchar>(i,j) = image.at<cv::Vec3b>(i,j)[0]*0.114
                                      + image.at<cv::Vec3b>(i,j)[1]*0.587
                                      + image.at<cv::Vec3b>(i,j)[2]*0.299;
            }


    }
    stop = clock() - start;
    cout << "time: " << stop * 1.0 / CLOCKS_PER_SEC << endl;

    return 0;
}

结果:

normal time: 0.035253
openmp time: 0.069894

0 个答案:

没有答案