主頁 > 作業系統 > 為什么使用OpenMP的多執行緒嵌套for回圈不會更快?

為什么使用OpenMP的多執行緒嵌套for回圈不會更快?

2022-01-13 17:19:02 作業系統

我撰寫了一個帶有以下 5 個引數的函式:

  1. 文本行陣列;
  2. 一些單詞的陣列;
  3. 行數(大約 40k);
  4. 字數(約 4-5);
  5. 要創建的執行緒數(k,嘗試了許多值,例如 2<k<20)。

該函式在for回圈中搜索給定的單詞,在每次迭代中掃描每一行以查找一個單詞(outer for)。

for回圈:

  • 回圈通過線;
  • 檢查該行是否包含給定的單詞;
  • 計算該單詞在該行中的出現次數;
  • 如果在該行中找到該單詞,則列印一條訊息;
  • 增加該單詞在整個文本中的出現次數及其在該行中的出現次數。

我先將其撰寫為串行程式,然后嘗試使用 OpenMP 將其并行化,并比較每個分析整個文本所需的時間。不幸的是,與串行版本相比,我無法提高并行程式的時間。

為了測量時間,我使用以下功能:

double ClockCounter;

void start()
{
        ClockCounter = omp_get_wtime();
}

void stop()
{
        ClockCounter = omp_get_wtime() - ClockCounter;
        printf("Elapsed time: %f\n", ClockCounter);
}

以及文本分析功能:

void analyze_text(char **lines, char *words[], size_t nr_lines, int nr_words, int k) {
        int i, total_word_count, word_occurence;
        start();
#       pragma omp parallel for num_threads(k) \
        default(none) shared(total_word_count, word_occurence) private(i, j, nr_words, nr_lines, word_occurence, counter)
        for (i=0; i<nr_words; i  ) {
                total_word_count = 0;
                size_t j;
                printf("The word is: %s.\nSEARCHING...\n", words[i]);
//#             pragma omp parallel for num_threads(k) \
//              default(none) shared(total_word_count) private(j, nr_lines, word_occurence, counter)
                for (j=0; j<nr_lines; j  ) {
                        char *line = NULL;
                        line = (char *) malloc (strlen(lines[j])   1);
                        strcpy(line, lines[j]);
                        word_occurence = 0;
                        if (strstr(line, words[i]) != NULL) {
                                printf("Word found at line %ld, position(s): ", j);
                                char *found_word = NULL;
                                found_word = (char *) malloc (strlen(words[i])  1);
                                char delim[] = " -";
                                char *ptr = strtok(line, delim);
                                int counter =  0;
                                while (ptr != NULL) {
                                        counter  ;
                                        strncpy(found_word, ptr, strlen(words[i]));
                                        found_word[strlen(found_word)] = '\0';
                                        if (strcmp(words[i], found_word) == 0) {
                                                word_occurence  ;
                                                printf("%d ", counter);
                                        }
                                        ptr =  strtok(NULL, delim);

                                }
                                printf("\nline[%3zu]: %s\n", j, lines[j]);
                        }
                        total_word_count  = word_occurence;
                }
                printf("The word appears %d times in the text in total.\n\n", total_word_count);
        }
        stop();
}

正如你所看到的,我也只嘗試并行化內部for回圈,但我也沒有得到任何改進。由于嵌套for回圈有點混亂,我不確定在哪里以及如何宣告并行 for 指令,也不知道如何正確地將變數設定為共享或私有。

順序版本看起來完全相同,但沒有宣告 omp 指令。

順序版本的時間(~=):

Elapsed time: 0.025583

Time (~=) with the parallel version (k=2, 4, 6, 8, always the same):

Elapsed time: 0.025690

Can somebody please explain to me what I am missing here?

uj5u.com熱心網友回復:

TL;DR 答案:您的代碼受記憶體限制(大量或記憶體讀取或寫入,實際上沒有 CPU 密集型計算)。CPU 很容易超過可用記憶體帶寬,增加執行緒數不會提高性能。這可能發生在您的硬體上,令人驚訝的是,這也發生在 Compiler Explorer 上,但不會發生在我的計算機上。我真的很困惑。

詳細解答:

您的代碼存在一些問題(資料爭用、記憶體泄漏、變數在資料子句中出現多次等),因此我執行了以下操作來修復這些錯誤并使您的代碼更快:

  1. 在最小要求范圍內使用變數。它有助于避免資料競爭并幫助編譯器進行更好的優化。
  2. 更正了 OpenMP 指令。i回圈之前,您必須添加以下行:
#pragma omp parallel for num_threads(k) default(none) shared(lines, words, nr_words, nr_lines)

另一種選擇是并行化j回圈。為避免競爭條件,您必須使用歸約 ( reduction( :total_word_count)):

#pragma omp parallel for num_threads(k) default(none) shared(i,lines, words, nr_words, nr_lines) reduction( :total_word_count)
  1. 去掉了耗時malloc,換成靜態分配:
//Maximum length of a line - modify it as necessary and make sure that no lines are longer than this value
#define MAX_LINE_LEN 1000

...
char line[MAX_LINE_LEN]; 
....
char found_word[MAX_LINE_LEN]; //it may be smaller
  1. strcpy(line, lines[j]);在隨后的if宣告之后被移動這非常耗時,并且僅在找到單詞時才需要。所以
char *line = NULL;
line = (char *) malloc (strlen(lines[j])   1);
strcpy(line, lines[j]);
word_occurence = 0;
if (strstr(line, words[i]) != NULL) {

改為

int word_occurence = 0;
if (strstr(lines[j], words[i]) != NULL) {
  char line[MAX_LINE_LEN];                        
  strcpy(line, lines[j]);
  ...
  //Note that the code below is not critical (rarely executed)...
  1. 將所有printf功能更改
#ifdef USE_PRINTF
 printf(...);
#endif

因此很容易打開/關閉列印輸出,也更容易測驗其性能。請注意,如果使用更多執行緒,列印輸出將混合在一起,因此您必須先收集輸出并稍后列印。

  1. 請注意,最好重寫代碼并首先遍歷文本行并在一行中搜索每個單詞。在這種情況下,快取利用率會更好,這將提高性能。

  2. 添加了一個主要功能來創建文本(通過從 5 個預定義的行中隨機添加行)來測驗其性能

代碼如下:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <omp.h>

//Maximum length of a line - modify it as necessary and make sure that no lines are longer than this value
#define MAX_LINE_LEN 1000

//Uncomment this line to see printout
//#define USE_PRINTF

double ClockCounter;
void start()
{
        ClockCounter = omp_get_wtime();
}

void stop()
{
        ClockCounter = omp_get_wtime() - ClockCounter;
        printf("Elapsed time: %f\n", ClockCounter);
}


void analyze_text(char **lines, const char *words[], const size_t nr_lines, const int nr_words, const int k) {
        start();
        #pragma omp parallel for num_threads(k) default(none) shared(lines, words, nr_words, nr_lines) 
        for (int i=0; i<nr_words; i  ) {
                int total_word_count = 0;
                #ifdef USE_PRINTF
                printf("The word is: %s.\nSEARCHING...\n", words[i]);
                #endif
                //#pragma omp parallel for num_threads(k) default(none) shared(i,lines, words, nr_words, nr_lines) reduction( :total_word_count)
                for (size_t j=0; j<nr_lines; j  ) {
                        int word_occurence = 0;
                        if (strstr(lines[j], words[i]) != NULL) {
                                char line[MAX_LINE_LEN];                        
                                strcpy(line, lines[j]);
                                #ifdef USE_PRINTF
                                  printf("Word found at line %ld, position(s): ", j);
                                #endif
                                char found_word[MAX_LINE_LEN]; 
                                char delim[] = " -";
                                char *ptr = strtok(line, delim);
                                int counter =  0;
                                while (ptr != NULL) {
                                        counter  ;
                                        strncpy(found_word, ptr, strlen(words[i]));
                                        found_word[strlen(found_word)] = '\0';
                                        if (strcmp(words[i], found_word) == 0) {
                                                word_occurence  ;
                                                #ifdef USE_PRINTF
                                                printf("%d ", counter);
                                                #endif
                                        }
                                        ptr =  strtok(NULL, delim);

                                }
                                #ifdef USE_PRINTF
                                printf("\nline[%3zu]: %s\n", j, lines[j]);
                                #endif
                        }
                        total_word_count  = word_occurence;
                }
                #ifdef USE_PRINTF
                printf("The word appears %d times in the text in total.\n\n", total_word_count);
                #endif
        }
        stop();
}

int main(){    
    const size_t nr_lines=40000;
    char* lines[nr_lines];
    //sample lines, the text have these lines in a random order
    const char* samples[]={
        "xxx yyy zzz qqq sss dddd aaaaa bbbbb cccc dd eeee fff ggg hh iii jjj kkkk llll mmm nnn oo pppp qqq rrrr ssss ttt",
        "one yyy zzz qqq sss dddd aaaaa bbbbb cccc dd eeee fff ggg hh iii jjj kkkk llll mmm nnn oo pppp qqq rrrr ssss ttt",
        "xxx two zzz qqq sss dddd aaaaa bbbbb cccc dd eeee fff ggg hh iii jjj kkkk llll mmm nnn oo pppp qqq rrrr ssss ttt",
        "xxx yyy three qqq sss dddd aaaaa bbbbb cccc dd eeee fff ggg hh iii jjj kkkk llll mmm nnn oo pppp qqq rrrr ssss ttt",
        "xxx yyy zzz four sss dddd aaaaa bbbbb cccc dd eeee fff ggg hh iii jjj kkkk llll mmm nnn oo pppp qqq rrrr ssss ttt",
        "xxx yyy zzz qqq five dddd aaaaa bbbbb cccc dd eeee fff ggg hh iii jjj kkkk llll mmm nnn oo pppp qqq rrrr ssss ttt"
    };


    for(size_t i=0;i<nr_lines;  i){
        unsigned long int rnd=rand()%1000;
        rnd = rnd >= sizeof(samples)/sizeof(samples[0]) ? 0 : rnd;
        lines[i]=(char*) malloc(strlen(samples[rnd]) 1);
        strcpy(lines[i],samples[rnd]);

    }
    
    printf("nr_lines=%ld\n",nr_lines);

    const char* words[]={"one", "two", "three", "four","five"};
    const size_t nr_words=sizeof(words)/sizeof(words[0]);

    printf("nr_words=%ld\n",nr_words);

    for(int i=1;i<6;i  )
    {
        printf("Threads used=%d  --- ",i);
        analyze_text(lines, words, nr_lines, nr_words, i);
    }
  // You should free allocated memory here.
  return 0;
}

我已經測驗了代碼首先i使用 400000 行(注意 40000 實在是太快了,所以我使用的行數比你多 10 倍)和Compiler Explorer上的 5 個單詞并行化了第一個 ( ) 回圈,結果是:

nr_lines=400000
nr_words=5
Threads used=1  --- Elapsed time: 0.032551
Threads used=2  --- Elapsed time: 0.028461
Threads used=3  --- Elapsed time: 0.029304
Threads used=4  --- Elapsed time: 0.027002
Threads used=5  --- Elapsed time: 0.026587

在我的筆記本電腦上,使用內核進行縮放要好得多:

gcc 5.c -fopenmp -O3 -mavx2  && ./a.out
nr_lines=400000
nr_words=5
Threads used=1  --- Elapsed time: 0.046173
Threads used=2  --- Elapsed time: 0.028958
Threads used=3  --- Elapsed time: 0.019951
Threads used=4  --- Elapsed time: 0.015462
Threads used=5  --- Elapsed time: 0.020994

我還并行化了第二個回圈(在這種情況下,第一個回圈沒有并行化以避免嵌套并行)。編譯器資源管理器上的結果:

nr_lines=400000
nr_words=5
Threads used=1  --- Elapsed time: 0.032781
Threads used=2  --- Elapsed time: 0.026288
Threads used=3  --- Elapsed time: 0.026601
Threads used=4  --- Elapsed time: 0.027013
Threads used=5  --- Elapsed time: 0.027567

在我的筆記本電腦上:

gcc 5.c -fopenmp -O3 -mavx2  && ./a.out
nr_lines=400000
nr_words=5
Threads used=1  --- Elapsed time: 0.047092
Threads used=2  --- Elapsed time: 0.024240
Threads used=3  --- Elapsed time: 0.016849
Threads used=4  --- Elapsed time: 0.014475
Threads used=5  --- Elapsed time: 0.012770
Threads used=6  --- Elapsed time: 0.011703
Threads used=7  --- Elapsed time: 0.009543
Threads used=8  --- Elapsed time: 0.012953

你可以看到

  1. 在 Compiler Explorer 上獲得的結果令人失望。我根本不知道它的原因是什么。很可能它與記憶體帶寬/記憶體訪問的可用通道有關,但我想高端處理器用于托管 Compiler Explorer。

  2. 在我的筆記本電腦上,縮放要好得多,特別是如果第二個回圈是并行的。這并不奇怪,因為在這種情況下快取利用率要好得多。因此我建議你重寫你的代碼并首先遍歷行并在一行中搜索所有單詞。

最后說明:如果性能很關鍵,很可能您可以找到一個并行庫,該庫旨在盡可能高效地執行此類搜索。

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/409608.html

標籤:

上一篇:我可以無限期地在Android中運行后臺執行緒嗎?

下一篇:如何在Python執行緒中不加鎖地讀取變數?

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • CA和證書

    1、在 CentOS7 中使用 gpg 創建 RSA 非對稱密鑰對 gpg --gen-key #Centos上生成公鑰/密鑰對(存放在家目錄.gnupg/) 2、將 CentOS7 匯出的公鑰,拷貝到 CentOS8 中,在 CentOS8 中使用 CentOS7 的公鑰加密一個檔案 gpg -a ......

    uj5u.com 2020-09-10 00:09:53 more
  • Kubernetes K8S之資源控制器Job和CronJob詳解

    Kubernetes的資源控制器Job和CronJob詳解與示例 ......

    uj5u.com 2020-09-10 00:10:45 more
  • VMware下安裝CentOS

    VMware下安裝CentOS 一、軟硬體準備 1 Centos鏡像準備 1.1 CentOS鏡像下載地址 下載地址 1.2 CentOS鏡像下載程序 點擊下載地址進入如下圖的網站,選擇需要下載的版本,這里選擇的是Centos8,點擊如圖所示。 決定選擇Centos8后,選擇想要的鏡像源進行下載,此 ......

    uj5u.com 2020-09-10 00:12:10 more
  • 如何使用Grep命令查找多個字串

    如何使用Grep 命令查找多個字串 大家好,我是良許! 今天向大家介紹一個非常有用的技巧,那就是使用 grep 命令查找多個字串。 簡單介紹一下,grep 命令可以理解為是一個功能強大的命令列工具,可以用它在一個或多個輸入檔案中搜索與正則運算式相匹配的文本,然后再將每個匹配的文本用標準輸出的格式 ......

    uj5u.com 2020-09-10 00:12:28 more
  • git配置http代理

    git配置http代理 經常遇到克隆 github 慢的問題,這里記錄一下幾種配置 git 代理的方法,解決 clone github 過慢。 目錄 git配置代理 git單獨配置github代理 git配置全域代理 配置終端環境變數 git配置代理 主要使用 git config 命令 git單獨 ......

    uj5u.com 2020-09-10 00:12:33 more
  • Linux npm install 裝包時提示Error EACCES permission denied解

    npm install 裝包時提示Error EACCES permission denied解決辦法 ......

    uj5u.com 2020-09-10 00:12:53 more
  • Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包

    Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包。 18 (flaskApi) [root@67 flaskDemo]# yum -y install nginx 19 已加載插件:fastestmirror, langpacks 20 Loading ......

    uj5u.com 2020-09-10 00:13:13 more
  • Linux查看服務器暴力破解ssh IP

    在公網的服務器上經常遇到別人爆破你服務器的22埠,用來挖礦或者干其他嘿嘿嘿的事情~ 這種情況下正確的做法是: 修改默認ssh的22埠 使用設定密鑰登錄或者白名單ip登錄 建議服務器密碼為復雜密碼 創建普通用戶登錄服務器(root權限過大) 建立堡壘機,實作統一管理服務器 統計爆破IP [root ......

    uj5u.com 2020-09-10 00:13:17 more
  • CentOS 7系統常見快捷鍵操作方式

    Linux系統中一些常見的快捷方式,可有效提高操作效率,在某些時刻也能避免操作失誤帶來的問題。 ......

    uj5u.com 2020-09-10 00:13:31 more
  • CentOS 7作業系統目錄結構介紹

    作業系統存在著大量的資料檔案資訊,相應檔案資訊會存在于系統相應目錄中,為了更好的管理資料資訊,會將系統進行一些目錄規劃,不同目錄存放不同的資源。 ......

    uj5u.com 2020-09-10 00:13:35 more
最新发布
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:43:21 more
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:42:36 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:26:53 more
  • 設定Windows主機的瀏覽器為wls2的默認瀏覽器

    這里以Chrome為例。 1. 準備作業 wsl是可以使用Windows主機上安裝的exe程式,出于安全考慮,默認情況下改功能是無法使用。要使用的話,終端需要以管理員權限啟動。 我這里以Windows Terminal為例,介紹如何默認使用管理員權限打開終端,具體操作如下圖所示: 2. 操作 wsl ......

    uj5u.com 2023-04-19 09:25:49 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:19:04 more
  • Linux學習筆記

    IP地址和主機名 IP地址 ifconfig可以用來查詢本機的IP地址,如果不能使用,可以通過install net-tools安裝。 Centos系統下ens33表示主網卡;inet后表示IP地址;lo表示本地回環網卡; 127.0.0.1表示代指本機;0.0.0.0可以用于代指本機,同時在放行設 ......

    uj5u.com 2023-04-18 06:52:01 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:50 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:01 more
  • 你是不是暴露了?

    作者:袁首京 原創文章,轉載時請保留此宣告,并給出原文連接。 如果您是計算機相關從業人員,那么應該經歷不止一次網路安全專項檢查了,你肯定是收到過資訊系統技術檢測報告,要求你加強風險監測,確保你提供的系統服務堅實可靠了。 沒檢測到問題還好,檢測到問題的話,有些處理起來還是挺麻煩的,尤其是線上正在運行的 ......

    uj5u.com 2023-04-05 16:52:56 more
  • 細節拉滿,80 張圖帶你一步一步推演 slab 記憶體池的設計與實作

    1. 前文回顧 在之前的幾篇記憶體管理系列文章中,筆者帶大家從宏觀角度完整地梳理了一遍 Linux 記憶體分配的整個鏈路,本文的主題依然是記憶體分配,這一次我們會從微觀的角度來探秘一下 Linux 內核中用于零散小記憶體塊分配的記憶體池 —— slab 分配器。 在本小節中,筆者還是按照以往的風格先帶大家簡單 ......

    uj5u.com 2023-04-05 16:44:11 more