c++ - 我使用 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 为字符返回单词反转字符(对于此任务,回文也是在单词列表中找到反向的单词,例如锯-是。
解决方案
每个任务执行的计算量(CPU 周期)是否弥补了为生成它们所做的工作?
我可能会建议#pragma omp parallel for
在这里使用 over the tasks,因为您的单词集在整个操作期间具有固定大小。然而,问题在于将单词插入palindromes
列表时的关键会话。
推荐阅读
- python - Python中的二进制加法进位和溢出
- python - 如何在 Python 中将 ndjson 文件转换为 csv 文件?
- json - 如何在 SQL Server 中创建父子字符串
- python-3.x - 用户未登录系统时如何使用pywinauto进行点击操作?
- git - 如何配置系统通过 ssh 反向隧道/代理使用 git?
- javascript - React 中 Context API 和 Next js 路由之间的冲突
- d3.js - 更改显示的 x 轴上刻度标签的数量?
- php - 使用PHPUnit更新数据的Laravel测试,断言两个字符串相等失败
- r - 如何使用 R 从 MATLAB 序列日期号转换日期?
- flutter - 如何解决:Gradle 任务 assembleDebug failed with exit code 1 error?用于视频压缩