为什么我的空间哈希这么慢?我正在编写一个使用平滑粒子流体动力学来模拟滑坡运动的代码。在光滑粒子流体动力学中,每个粒子都会影响 3 个“光滑长度”距离内的粒子。我正在尝试实现空间散列函数,以便快速查找相邻粒子。
对于我的实现,我使用了 stl 中的“set”数据类型。在每个时间步,使用下面的函数将粒子散列到它们的桶中。“bucket”是一个集合向量,每个网格单元有一个集合(空间域是有限的)。每个粒子由一个整数标识。
为了寻找碰撞,使用下面标题为“getSurroundingParticles”的函数,它接受一个整数(对应于一个粒子)并返回一个集合,该集合包含粒子的 3 个支撑长度内的所有网格单元。
问题是,当粒子数为 2000 时,这个实现真的很慢,甚至比检查每个粒子与其他粒子还要慢。我希望有人能在我的实现中发现一个我没有看到的明显问题。
//put each particle into its bucket(s)
void hashParticles()
{
int grid_cell0;
cellsWithParticles.clear();
for(int i = 0; i<N; i++)
{
//determine the four grid cells that surround the particle, as well as the grid cell that the particle occupies
//using the hash function int grid_cell = ( floor(x/cell size) ) + ( floor(y/cell size) )*width
grid_cell0 = ( floor( (Xnew[i])/cell_spacing) ) + ( floor(Ynew[i]/cell_spacing) )*cell_width;
//keep track of cells with particles, cellsWithParticles is an unordered set so duplicates will automatically be deleted
cellsWithParticles.insert(grid_cell0);
//since each of the hash buckets is an unordered set any duplicates will be deleted
buckets[grid_cell0].insert(i);
}
}
set<int> getSurroundingParticles(int particleOfInterest)
{
set<int> surroundingParticles;
int numSurrounding;
float divisor = (support_length/cell_spacing);
numSurrounding = ceil( divisor );
int grid_cell;
for(int i = -numSurrounding; i <= numSurrounding; i++)
{
for(int j = -numSurrounding; j <= numSurrounding; j++)
{
grid_cell = (int)( floor( ((Xnew[particleOfInterest])+j*cell_spacing)/cell_spacing) ) + ( floor((Ynew[particleOfInterest]+i*cell_spacing)/cell_spacing) )*cell_width;
surroundingParticles.insert(buckets[grid_cell].begin(),buckets[grid_cell].end());
}
}
return surroundingParticles;
}
看起来调用 getSurroundingParticles 的代码:
set<int> nearbyParticles;
//for each bucket with particles in it
for ( int i = 0; i < N; i++ )
{
nearbyParticles = getSurroundingParticles(i);
//for each particle in the bucket
for ( std::set<int>::iterator ipoint = nearbyParticles.begin(); ipoint != nearbyParticles.end(); ++ipoint )
{
//do stuff to check if the smaller subset of particles collide
}
}
非常感谢!