读取文件时无法使用 OpenMP 获得加速

Couldn't get acceleration using OpenMP while reading files

本文关键字:OpenMP 加速 文件 读取      更新时间:2023-10-16

我尝试使用 OpenMP 读取 500M 的C++文件。我将文件拆分为一些块,每次并行加载"kill"记录,重复。

我正在使用gcc编译文件(g ++ mytest.cpp -o mytest -fopenmp(在ubuntu上工作。

在这里我提供代码:

(我删除了一些代码,以使 ReadFile 功能更加突出。

map<unsigned int, int> Node2Num;
typedef struct {
unsigned int num;
set<unsigned int>adj;
}node; 
node Gnode[4800000];
void ReadFile()
{
ifstream input("./soc-LiveJournal1.bin", ios::in | ios::binary);
cout << "start to read the file..." << endl;
//to get the size of the file
input.seekg(0, ios_base::end);
size_t fileSize = input.tellg();
input.seekg(0, ios_base::beg);
//to split the file into ReadTime blocks
int EdgesInFile = fileSize / 8; 
int ReadTime = EdgesInFile / PerEdges;
unsigned int buffer[2*PerEdges];
int tid, i, j, killed;
unsigned int src, des;
volatile int cnt = 0; //all the nodes stored in the file
#pragma omp parallel for num_threads(16) private(i,buffer,killed,j,src,des,kk,tid) firstprivate(ReadTime,EdgesInFile)
for(i = 0;i < ReadTime+1;i++){
#pragma omp critical
{
input.read((char*)buffer, sizeof(buffer));
cout<<"Thread Num:"<<omp_get_thread_num()<<" Read Time:"<<i<<endl;
}
killed = PerEdges;
if(i == ReadTime) 
killed = EdgesInFile - ReadTime*PerEdges; 
for(j = 0;j < killed;j++) {
src = (unsigned int)buffer[j];
des = (unsigned int)buffer[j+1];
#pragma omp critical
{
//to store the src and des... 
}
}
}
cout << "finish the reading!" << endl;
input.close();
}
int main()
{
clock_t T1 = clock();
ReadFile(); 
clock_t T2 = clock();
cout<< "Reading Time:" << (double)(T2 - T1) / CLOCKS_PER_SEC << "seconds" << endl;
return 0;
}

我在代码中读取的文件存储了一个图,由连续的线条组成,每行(8字节(包括两个连续节点——源节点(4字节(和目标节点(4字节(。节点号存储为无符号 int 类型。

但是我无法通过添加 #pragma 子句来获得任何加速。阅读时间与OpenMP无关,也与我在 #pragma 子句中设置的num_threads没有联系。阅读时间相同,约200秒。

谁能告诉我问题出在哪里?

您在 I/O 操作之前添加#pragma omp critical是对的!

然而

omp 关键指令标识必须 一次由单个线程执行。

循环中的大部分代码都在 omp 关键部分。其余代码不消耗 CPU。

因此,您观察到的是正常的。

除非您使用并行文件系统,否则使用 OpenMP 几乎无法提高 I/O 操作的性能。
OpenMP 实际上是为了改善 CPU 密集型部分。