用了openmp后效率更低,问什么?
如下代码是从两个文件中读取数据的程序,一个没有用多线程,一个用了多线程,后者反而比前者慢了3倍。各位帮我分析一下原因:
DWORD preTick = GetTickCount();
// read the geometry input file
ifstream streamGeom;
streamGeom.open(geomFile);
int numOfTriangles = 0;
streamGeom >> numOfTriangles;
F3d* vertexBuffer = new F3d[numOfTriangles * 3];
for (int i = 0; i < numOfTriangles * 3; i++)
{
streamGeom >> vertexBuffer[i].x >> vertexBuffer[i].y >> vertexBuffer[i].z;
}
streamGeom.close();
// read the ray input file
ifstream streamRay;
streamRay.open(rayFile);
int numOfRays = 0;
streamRay >> numOfRays;
F3d* rayOrigins = new F3d[numOfRays];
F3d* rayDirections = new F3d[numOfRays];
for (int i = 0; i < numOfRays; i++)
{
streamRay >> rayOrigins[i].x >> rayOrigins[i].y >> rayOrigins[i].z;
streamRay >> rayDirections[i].x >> rayDirections[i].y >> rayDirections[i].z;
}
streamRay.close();
多线程的代码:
DWORD preTick = GetTickCount();
// read the geometry input file
ifstream fstreamGeom;
fstreamGeom.open(geomFile);
ostringstream ostreamGeom;
ostreamGeom << fstreamGeom.rdbuf();
istringstream streamGeom(ostreamGeom.str());
fstreamGeom.close();
ifstream fstreamRay;
fstreamRay.open(rayFile);
ostringstream ostreamRay;
ostreamRay << fstreamRay.rdbuf();
istringstream streamRay(ostreamRay.str());
fstreamRay.close();
int numOfTriangles = 0;
streamGeom >> numOfTriangles;
F3d* vertexBuffer = new F3d[numOfTriangles * 3];
int numOfRays = 0;
streamRay >> numOfRays;
F3d* rayOrigins = new F3d[numOfRays];
F3d* rayDirections = new F3d[numOfRays];
printf( "Read time=%d\n", GetTickCount()-preTick);
preTick = GetTickCount();
#pragma omp parallel sections
{
#pragma omp section
{
for (int i = 0; i < numOfTriangles * 3; i++)
{
streamGeom >> vertexBuffer[i].x >> vertexBuffer[i].y >> vertexBuffer[i].z;
}
}
#pragma omp section
{
for (int i = 0; i < numOfRays; i++)
{
streamRay >> rayOrigins[i].x >> rayOrigins[i].y >> rayOrigins[i].z;
streamRay >> rayDirections[i].x >> rayDirections[i].y >> rayDirections[i].z;
}
}
}
printf( "Read time=%d\n", GetTickCount()-preTick);