• Create Account

# A* speed issues (C++)

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

8 replies to this topic

### #1zalzane  Members   -  Reputation: 191

Like
0Likes
Like

Posted 05 February 2012 - 11:49 PM

I've been working on this code for quite awhile now trying to get it to run in a reasonable amount of time. It's supposed to be an A* algo that pathfinds between two points while taking into considering a cost grid that represents how hard it is to cross each tile. A typical grid that would be fed to the algo would be 256x256 tiles in size. During profiling I would test between one end of the grid (0,0) to the other end (255,255) and would get atrocious speeds of up to 60 seconds. There isn't much in the algo that strikes me as any kind of heavy lifting, so I'm virtually clueless as to why it's running so slow.

Here's the code, I put all the structure definitions involved and did some hardcore commenting. The indenting may be weird because of how the forum interprets whatever the hell my text editor is using for spaces.

struct pair_s{
int x;
int y;
pair_s(int x_, int y_){
x = x_;
y = y_;
}
};
struct node_s{
vector<pair_s> pathToNode;
int x,y;
float distToDest;
float costTravelled;
float cumulativeCost;
bool hasNodeBeenParsed;
node_s(int x_, int y_, float distToDest_, float costTravelled_, vector<pair_s>* prevPath){
x = x_;
y = y_;
distToDest = distToDest_;
costTravelled = costTravelled_;
hasNodeBeenParsed = false;
cumulativeCost = costTravelled + distToDest;
if(prevPath != NULL){
pathToNode = (*prevPath);
pathToNode.push_back(pair_s(x,y));//add the current node to path history
}
}
};

void worldgen_c::getPathBetweenPointsAstr(int initial_x, int initial_y, int dest_x, int dest_y, vector<vector<float> >* costMap, vector<pair_s>* retPath, float costMultiplier){
vector<node_s> closedNodes;
vector<node_s> openNodes;
int gridWidth = costMap->size();
bool** nodesAcctFor = new bool*[gridWidth];//when it comes to checking if a tile has already been added to the node vectors,
for(int i=0; i<gridWidth; i++){//it's more efficent to use a 2d array of booleans rather than iterating through a list of coordinates
nodesAcctFor[i] = new bool[gridWidth];
}
for(int x=0; x<gridWidth; x++){
for(int y=0; y<gridWidth; y++){
nodesAcctFor[x][y]=false;
}
}
//initial node
closedNodes.push_back( node_s(initial_x, initial_y, getDist(initial_x, initial_y, dest_x, dest_y), (*costMap)[initial_x][initial_y]*costMultiplier, NULL) );
while(1){
//first we add spots adjacent to closed nodes to the open nodes
for(int node=0; node<closedNodes.size(); node++){
for(int x_off=-1; x_off<=1; x_off++){ //checking cardinals and diagonals
for(int y_off=-1; y_off<=1; y_off++){
if(x_off==0 && y_off==0)//we dont care about the node we're sitting on
continue;
if(closedNodes[node].x+x_off>=gridWidth || closedNodes[node].x+x_off<0 || closedNodes[node].y+y_off<0 || closedNodes[node].y+y_off>=gridWidth)//make sure node within b ounds
continue;
if(nodesAcctFor[closedNodes[node].x+x_off][closedNodes[node].y+y_off])//making sure node isnt already added to one of the tree things
continue;
//now add the node to the openNodes vector
float pathcost=1;
if(x_off != 0 && y_off != 0) //if going diagonally, higher pathcost
pathcost=1.4;
openNodes.push_back(node_s(
closedNodes[node].x+x_off, //x val
closedNodes[node].y+y_off, //y val
getDist(closedNodes[node].x+x_off, closedNodes[node].y+y_off, dest_x, dest_y),//distance to destination
closedNodes[node].costTravelled + (*costMap)[closedNodes[node].x+x_off][closedNodes[node].y+y_off]*costMultiplier + pathcost, //heuristic cost
&closedNodes[node].pathToNode//path to old node
) );
nodesAcctFor[closedNodes[node].x+x_off][closedNodes[node].y+y_off] = true;
}
}
closedNodes[node].hasNodeBeenParsed = true;
}
}

//now we check each open node and see which one has the lowest cumulative cost
int lowestCostIndex=-1;
float lowestCostValue = 4294967296;
for(int i=0; i<openNodes.size(); i++){
if( openNodes[i].cumulativeCost < lowestCostValue ){
lowestCostValue = openNodes[i].cumulativeCost;
lowestCostIndex = i;
}
}
//now convert the open node to a closed node
closedNodes.push_back( openNodes[lowestCostIndex] );
openNodes.erase(lowestCostIndex + openNodes.begin() );

if(closedNodes[closedNodes.size()-1].x == dest_x && closedNodes[closedNodes.size()-1].y == dest_y){ //see if we're finally done
(*retPath) = closedNodes[closedNodes.size()-1].pathToNode;
break;
}
}
for(int i=0; i<gridWidth; i++){//cleanup
delete[] nodesAcctFor[i];
}
delete[] nodesAcctFor;
return;
}

### #2slicer4ever  GDNet+   -  Reputation: 6296

Like
1Likes
Like

Posted 06 February 2012 - 02:00 AM

ah, easy fix: binary heap sorting: http://www.policyalmanac.org/games/binaryHeaps.htm

you should see substancial improvment in speeds.
Check out https://www.facebook.com/LiquidGames for some great games made by me on the Playstation Mobile market.

### #3Postie  Members   -  Reputation: 1438

Like
1Likes
Like

Posted 06 February 2012 - 02:41 AM

There's a surprising amount of heavy lifting that occurs in the open and closed lists. If you profile your code you'll soon see where the real culprit is.

That said, you may not need to go to the extent of implementing a binary heap if you can reduce the number of members in the closed list. I had some speed issues in my first attempt at an A* implementation and refactored my code to make better use of the spatial partitioning my engine was already using and the performance was good enough without needing the complexity of a binary heap.

My game world is broken down into zones which are 32x32 tiles, so instead of storing tiles in the closed list, I stored Zones and a 1024bit array representing the traversal of each tile for the zone. To check the closed list I simply find the zone through a list scan then do some simple bit twiddling to find the tile itself, thus reducing the size of the closed list by a factor of between 100 to 1000.

Basically I was too lazy to learn how to implement a binary heap.

Another option is to do the pathfinding on a much coarser grid first, then pathfind between adjacent grids.
Currently working on an open world survival RPG - For info check out my Development blog:

### #4ssrun  Members   -  Reputation: 157

Like
1Likes
Like

Posted 06 February 2012 - 08:06 AM

As stated use a heap based priority queue to store the open list. Do not use a closed list at all, just store a flag on each tile representing whether it's open, closed or neither. Only clear the cost and parent pointers on the tile when you visit it for the first time in a particular A* session so that would mean encapsulating the algorithm in a class with a static variable that always increments a search id. Use hierarchical pathfinding A*. Hope that helps.

### #5zalzane  Members   -  Reputation: 191

Like
0Likes
Like

Posted 06 February 2012 - 09:33 PM

thanks guys, the issue was with the comparasion/sort stuff and binary heap thing pretty much fixed it

### #6Waterlimon  Crossbones+   -  Reputation: 4368

Like
1Likes
Like

Posted 07 February 2012 - 08:10 AM

Not sure if it works in all situations or at all, but try pathfinding from both the start and the end at the same time, and when the 2 spreading areas touch each other, get the path.

In some situations it will be slower than normal in some it should be faster. Also not sure if it works on other than grid like node system.

o3o

### #7Matt-D  Crossbones+   -  Reputation: 1572

Like
1Likes
Like

Posted 09 February 2012 - 12:54 PM

A few small notes, as with all the optimizations they might help or not (you should always profile to see), I've cut the quoted code just to the relevant parts:
- you're doing an awful lot of work in the constructors of pair_s and node_s, in particular assignments in a ctor body are a bad idea since they cause multiple (re)initializations when you instantiate objects (e.g., when constructing closedNodes here --
vector<node_s> closedNodes;
-- the objects contained in the container are constructed when the container itself is); use initialization lists instead: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6
- regarding nodesAcctFor -- 1D array may be faster than 2D array for nodesAcctFor, since it gives you contiguity (your CPU's cache lines will thank you) and avoids multiple heap allocations ("new" is a significantly expensive operation, you should avoid having it in a for loop if you can), see http://stackoverflow.com/questions/2151084/map-a-2d-array-onto-a-1d-array-c
- it might be a good idea to use size_t or ptrdiff_t (depends on whether you want signed or unsigned) instead of ints in your for loops when you use the iteration variable as an index to an array/container (and it expresses the intent more clearly, so a plus for readability), see: http://www.viva64.com/en/a/0050/

struct pair_s{
int x;
int y;
pair_s(int x_, int y_){
x = x_;
y = y_;
}
};
struct node_s{
node_s(int x_, int y_, float distToDest_, float costTravelled_, vector<pair_s>* prevPath){
x = x_;
y = y_;
distToDest = distToDest_;
costTravelled = costTravelled_;
hasNodeBeenParsed = false;
cumulativeCost = costTravelled + distToDest;
if(prevPath != NULL){
pathToNode = (*prevPath);
pathToNode.push_back(pair_s(x,y));//add the current node to path history
}
}
};

void worldgen_c::getPathBetweenPointsAstr(int initial_x, int initial_y, int dest_x, int dest_y, vector<vector<float> >* costMap, vector<pair_s>* retPath, float costMultiplier){
vector<node_s> closedNodes;
vector<node_s> openNodes;
int gridWidth = costMap->size();
bool** nodesAcctFor = new bool*[gridWidth];//when it comes to checking if a tile has already been added to the node vectors,
for(int i=0; i<gridWidth; i++){//it's more efficent to use a 2d array of booleans rather than iterating through a list of coordinates
nodesAcctFor[i] = new bool[gridWidth];
}
for(int x=0; x<gridWidth; x++){
for(int y=0; y<gridWidth; y++){
nodesAcctFor[x][y]=false;
}
}
// ... cut ...
}

### #8zalzane  Members   -  Reputation: 191

Like
0Likes
Like

Posted 09 February 2012 - 05:48 PM

A few small notes, as with all the optimizations they might help or not (you should always profile to see), I've cut the quoted code just to the relevant parts:
- you're doing an awful lot of work in the constructors of pair_s and node_s, in particular assignments in a ctor body are a bad idea since they cause multiple (re)initializations when you instantiate objects (e.g., when constructing closedNodes here --

vector<node_s> closedNodes;
-- the objects contained in the container are constructed when the container itself is); use initialization lists instead: http://www.parashift...s.html#faq-10.6
- regarding nodesAcctFor -- 1D array may be faster than 2D array for nodesAcctFor, since it gives you contiguity (your CPU's cache lines will thank you) and avoids multiple heap allocations ("new" is a significantly expensive operation, you should avoid having it in a for loop if you can), see http://stackoverflow...to-a-1d-array-c
- it might be a good idea to use size_t or ptrdiff_t (depends on whether you want signed or unsigned) instead of ints in your for loops when you use the iteration variable as an index to an array/container (and it expresses the intent more clearly, so a plus for readability), see: http://www.viva64.com/en/a/0050/

struct pair_s{
int x;
int y;
pair_s(int x_, int y_){
x = x_;
y = y_;
}
};
struct node_s{
node_s(int x_, int y_, float distToDest_, float costTravelled_, vector<pair_s>* prevPath){
x = x_;
y = y_;
distToDest = distToDest_;
costTravelled = costTravelled_;
hasNodeBeenParsed = false;
cumulativeCost = costTravelled + distToDest;
if(prevPath != NULL){
pathToNode = (*prevPath);
pathToNode.push_back(pair_s(x,y));//add the current node to path history
}
}
};

void worldgen_c::getPathBetweenPointsAstr(int initial_x, int initial_y, int dest_x, int dest_y, vector<vector<float> >* costMap, vector<pair_s>* retPath, float costMultiplier){
vector<node_s> closedNodes;
vector<node_s> openNodes;
int gridWidth = costMap->size();
bool** nodesAcctFor = new bool*[gridWidth];//when it comes to checking if a tile has already been added to the node vectors,
for(int i=0; i<gridWidth; i++){//it's more efficent to use a 2d array of booleans rather than iterating through a list of coordinates
nodesAcctFor[i] = new bool[gridWidth];
}
for(int x=0; x<gridWidth; x++){
for(int y=0; y<gridWidth; y++){
nodesAcctFor[x][y]=false;
}
}
// ... cut ...
}

oh wow, thanks for the incredible feedback.

It's not often that I can get feedback at that level of detail/insight, thank you.

### #9wodinoneeye  Members   -  Reputation: 1651

Like
1Likes
Like

Posted 09 February 2012 - 10:56 PM

I did a collaboration with another programmer many years ago (via Usenet, heh) helping to optimize his A* solution (2D grid based map) he actually did a real good visual interface that showed the algorithm executing and had many precanned testcases of 'problematic' terrain patterns, lots of variants (manhattan vs 8 adjacents), etc...

eventually used HeapQ
Minimizing the A* map data to fit in cache much better (packing/bitflags??/ints as small as possible)

another speedup (there were many small incrementals) was doing pointer math with map row spans when checking 8 adjacents (and for HeapQ as well)

another was if possible putting a edge of impassibles all around the map so that the x<0 X>mapsize y<0 y>mapsize tests for candidates didnt have to be done

with power of 2 mapsizes then shifts used instead of divides (actually did speed it up some small significant amount)

oh and proper inlining and other compiler optimizations made a huge difference in speed (I forget if we unwrapped the 8 adjacent loop)

even on my old 800mhz single core P4 laptop, a 512x512 greyscale picture maps solutions ran virtually instantaneously (he actually had performance tools built into the visual interface to do sets of 500-1000 random paths on a map....)
That even with more than a few 'modular' options with extra sub calls that once standardized could be eliminated (inlined)
--------------------------------------------Ratings are Opinion, not Fact

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

PARTNERS