C++程序无法扩展

C++ program doesn't scale

本文关键字:扩展 程序 C++      更新时间:2023-10-16

我有一个简单的小件代码,该代码在并行修改2D向量。我分别使用1和4个线程对其进行了测试。但是,我的加速速度不到2倍。我想不出任何原因不扩展。有人可以给我提示吗?谢谢!

#include<iostream>
#include<omp.h>
#include<vector>
#include<chrono>
#include<stdio.h>
using namespace std;
typedef std::chrono::milliseconds ms;
struct Dummy{
    char dummy[70];
    Dummy(){
        for(int i=0;i<70;i++){
            dummy[i]='a';
    }
    }
};
int main(){
    int num = 5000000;
    vector<vector<Dummy> >myvec(4, vector<Dummy>(num));
    auto start = std::chrono::high_resolution_clock::now();
    #pragma omp parallel for schedule(static)
    for(int i=0;i<4;i++){ //modifies myvec in parallel
        int tid = omp_get_thread_num();
        printf("Thread %d is going to workn",tid);
        for(int j=0;j<num;j++){
            myvec[i][j].dummy[0]='b';
        }
    }
    auto end = std::chrono::high_resolution_clock::now();
    cout<<"Time used: "<< std::chrono::duration_cast<ms>(end - start).count()<<"ms"<<endl;
    return 0;
}

在这种情况下,较差的缩放主要是由于您在平行部分中没有进行足够大的计算而引起的。在示例代码中,您的内存性能应该是最大的限制因素,并且在单个桌面/移动CPU上,内存子系统可能会由所有内核共享,因此您不应该期望良好的扩展。