什么可以阻止多处理提高速度 - OpenMP?

What can prevent multiprocessing from improving speed - OpenMP?

我正在扫描向量的每个排列,我想对这个过程进行多线程处理(每个线程都会扫描一些向量的所有排列)。 我设法提取了不会加速的代码(我知道它没有做任何有用的事情,但它重现了我的问题)。

int main(int argc, char *argv[]){

    std::vector<std::string *> myVector;
    for(int i = 0 ; i < 8 ; ++i){
        myVector.push_back(new std::string("myString" + std::to_string(i)));
    }
    std::sort(myVector.begin(), myVector.end());

    omp_set_dynamic(0);
    omp_set_num_threads(8);
#pragma omp parallel for shared(myVector)
    for(int i = 0 ; i < 100 ; ++i){

        std::vector<std::string*> test(myVector);
        do{ //here is a permutation
        } while(std::next_permutation(test.begin(), test.end())); // tests all the permutations of this combination

    }
    return 0;
}

结果是:

1 thread : 15 seconds
2 threads : 8 seconds
4 threads : 15 seconds
8 threads : 18 seconds
16 threads : 20 seconds

我正在使用 8 核 i7 处理器。我不明白 8 个线程怎么会比 1 个线程慢...我不认为创建新线程的成本比经历 40320 个排列的成本高..那么发生了什么?

感谢大家的帮助,我终于找到了答案:

有两个问题:

  1. 快速性能分析显示大部分时间都花在了 std::lockit 上,这是在 visual studio 上用于调试的东西。为了防止添加此命令行 /D "_HAS_ITERATOR_DEBUGGING=0" /D "_SECURE_SCL=0" .这就是为什么添加更多线程会导致时间损失
  2. 打开优化有助于提高性能