QThreadPool性能

时间:2015-11-18 02:35:51

标签: c++ multithreading qt threadpool

为什么我的4线程快速排序比1线程更慢? 使用MPI会给算法带来哪些好处? 对于n = 10000000; 时间正常:1.22s 时间线程数4:1.66s

main.cpp http://pastebin.com/eiqKraHB 标题http://pastebin.com/mkn3wyfZ

#include "quicksorttask.h"

#include <QThreadPool>
#include <QDebug>

QuickSortTask::QuickSortTask(int arr[], int left, int right):
    mArr{arr},
    mLeft{left},
    mRight{right}
{
}

void QuickSortTask::run()
{
    int i = mLeft, j = mRight;
    int pivot = mArr[(mLeft + mRight) / 2];

    int tmp;
    /* partition */
    while (i <= j)
    {
        while (mArr[i] < pivot)
        {
            i++;
        }
        while (mArr[j] > pivot)
        {
            j--;
        }
        if (i <= j)
        {
            tmp = mArr[i];
            mArr[i] = mArr[j];
            mArr[j] = tmp;
            i++;
            j--;
        }
    };

    /* recursion */
    if (mLeft < j)
    {
        if (abs(mLeft - j) > 100000)
        {
            QuickSortTask *task = new QuickSortTask(mArr, mLeft, j);
            QThreadPool::globalInstance()->start(task);
        }
        else
        {
            quickSort(mArr, mLeft, j);
        }
    }
    if (i < mRight)
    {
        if (abs(i - mRight) > 100000)
        {
            QuickSortTask *task = new QuickSortTask(mArr, i, mRight);
            QThreadPool::globalInstance()->start(task);
        }
        else
        {
            quickSort(mArr, i, mRight);
        }
    }
}

void QuickSortTask::quickSort(int arr[], int left, int right) {
    int i = left, j = right;
    int tmp;
    int pivot = arr[(left + right) / 2];

    /* partition */
    while (i <= j) {
        while (arr[i] < pivot)
            i++;
        while (arr[j] > pivot)
            j--;
        if (i <= j) {
            tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            i++;
            j--;
        }
    };

    /* recursion */
    if (left < j)
        quickSort(arr, left, j);
    if (i < right)
        quickSort(arr, i, right);
}

0 个答案:

没有答案