C++ 程序无法扩展

C++ program doesn't scale

我有一小段简单的代码可以并行修改二维向量。我分别使用 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 work\n",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 内存子系统可能会被所有内核共享,因此您不应期望良好的扩展性。