首页 > 解决方案 > 我使用 OpenMP 的线程越多,执行时间就越长,这是怎么回事?

问题描述

我编写了一个程序,该程序接收字典并查找字典中所有回文单词。我试图并行化这本词典的浏览,以及使用 OpenMP 检查单词是否为回文的逻辑的执行。但是,当我注意到执行时间随着我允许程序使用越来越多的线程而增加时。对此有何解释?我的代码中有错误吗?

#pragma omp parallel    //block of code that we want to execute using multiple threads
#pragma omp single  //we only want one thread to iterate through the foor loop and spawn tasks for the other threads
{
    #pragma omp task untied     /* iterating through the for loop is the main task, so 
                     * burden should be shared if execution is suspended
                     */
    {
        for (set<string>::iterator i = wordList.begin(); i != wordList.end(); ++i){
        #pragma omp task    //spawn the tasks of evaluating whether each word should be inserted into palindrome list
            {
                if (isPalindrome(*i)){  //if the word is by itself a palindrome, insert
                    palindromes.insert(*i);
                }
                /* if the reverse of the current word is in the wordlist and it hasn't already been inserted,
                 * insert them both into set of palindromes
                 */ 
                else if (wordList.find(reverseWord(*i)) != wordList.end()){
                    if(palindromes.find(*i) == palindromes.end()){
                        palindromes.insert(*i);
                        palindromes.insert(reverseWord(*i));
                    }
                }
            }
        }
    }
}

我使用对 omp_set_num_threads(Argv[1]) 的调用来更改运行时允许的最大线程数。我在超级计算机上执行这个程序,所以我不认为这是我的计算机“过载”或其他问题的问题。是什么赋予了?我是否误解了如何使用 OpenMP?我在此代码块之前和之后使用了两次对 omp_get_wtime() 的调用来测量执行时间。

编辑:回文和 wordList 都是 std::set,isPalindrome 通过指针操作检查单词是否为回文,reverseWord 为字符返回单词反转字符(对于此任务,回文也是在单词列表中找到反向的单词,例如锯-是。

标签: c++concurrencyparallel-processingopenmp

解决方案


每个任务执行的计算量(CPU 周期)是否弥补了为生成它们所做的工作?

我可能会建议#pragma omp parallel for在这里使用 over the tasks,因为您的单词集在整个操作期间具有固定大小。然而,问题在于将单词插入palindromes列表时的关键会话。


推荐阅读