Bottle neck in A star algorithm

Mar 1, 2014 at 11:27am
Recently I am learning a path finding algorithm,
actually I have learn BFS around 2 year ago but doesn't learn more about path finding after that.
So I am coding an a star for my game. when it comes to complexity it's guaranteed that a star win.
I cheat a star algorithm a bit so shortest path isn't always the answer but it runs quicker.

here is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#include <iostream>
#include <queue>
#include <vector>
#include <map>
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <tuple>
#include <set>
#include <cmath>
#include <cassert>

using namespace std;

typedef pair< int, int > Point;

// maximum width
const int mWidth = 1000;
const int mHeight = 1000;

int mapWidth = 0;
int mapHeight = 0;

const int obstacle = -1;

int bitmap[mWidth][mHeight];
bool visited[mWidth][mHeight];

// graph for back tracking path
Point cameFrom[mWidth][mHeight];


int mDistance( const Point& a, const Point& b ){
    return (std::abs( a.first - b.first ) + std::abs( a.second - b.second ));
}

void printMap(){
    for( int y = 0; y < mapHeight; ++ y ){
        for( int x = 0; x < mapWidth; ++ x ){
            cout << setw(3) << bitmap[x][y];
        }
        cout << endl;
    }
}

// score, step, point
typedef tuple< int, int, Point > Node;

vector<Point> Astar( Point start, Point end, int& vc ){
    assert( mapWidth <= mWidth );
    assert( mapHeight <= mHeight );
    assert( 0 <= start.first && start.first < mapWidth );
    assert( 0 <= start.second && start.second < mapHeight );

    assert( 0 <= end.first && end.first < mapWidth );
    assert( 0 <= end.second && end.second < mapHeight );

    // clear previous memory
    memset( visited, 0, sizeof( visited ));
    memset( cameFrom, 0, sizeof( cameFrom ));

    priority_queue< Node, vector<Node>, greater<Node> > Q;

    // clostestPoint reachable by the unit if target cannot be reached
    // special case : distance, step, point
    Node clostestPoint = Node( mDistance( start, end), 0, start );

    auto reconstructPath = [&]( Point endPt )
    {
        vector<Point> path;

        int cx, cy;
        Point tmpPt;

        cx = endPt.first;
        cy = endPt.second;

        while( start.first != cx || start.second != cy ){
            path.push_back( Point( cx, cy ) );
            tmpPt = cameFrom[cx][cy];
            cx = tmpPt.first;
            cy = tmpPt.second;
        }

        return path;
    };


    auto push = [&]( const Point& from, int x, int y, int step )
    {

        if( x >= mapWidth || x < 0 || y >= mapHeight || y < 0 ) return;
        if( bitmap[x][y] == obstacle ) return;

//        if( visited[x][y] && step > bitmap[x][y] ) return;
        if( visited[x][y] ) return;
        visited[x][y] = true;


        const Point pt( x, y );

        int distance = mDistance( pt, end );

        if( get<0>(clostestPoint) > distance ||
            (get<0>(clostestPoint) == distance && get<1>(clostestPoint) > step )
           ) {
                clostestPoint = Node( distance, step, pt );
        }

        // add to open list
        Q.push( Node( step + distance * 3/2, step, pt ) );
        cameFrom[x][y] = from;
    };

    // special case if start point is an obstacle ignore it
    if( bitmap[ start.first ][ start.second ] == obstacle ) {
        bitmap[ start.first ][ start.second ] = 0;

        push( start, start.first, start.second, 0 );

        bitmap[ start.first ][ start.second ] = obstacle;
    }
    else {
        push( start, start.first, start.second, 0 );
    }

    while( !Q.empty() ){
        ++ vc;

        const Node current = Q.top();

        const Point cpoint = std::get<2>( current );
        const int cscore = std::get<0>( current );
        const int cstep = std::get<1>( current );


        if( cpoint == end ){
            return reconstructPath( end );
        }

        Q.pop();

        push( cpoint, cpoint.first + 1, cpoint.second, cstep + 1 );
        push( cpoint, cpoint.first - 1, cpoint.second, cstep + 1 );
        push( cpoint, cpoint.first, cpoint.second + 1, cstep + 1 );
        push( cpoint, cpoint.first, cpoint.second - 1, cstep + 1 );
    }

    return reconstructPath( get<2>(clostestPoint ) );
}

vector<Point> BFS( Point start, Point end, int& vcount ){
    memset( visited, false, sizeof( visited));
    // coordinate , back
    typedef tuple< Point, int > QNode;

    vector<QNode> Q = { QNode( start, -1 ) };


    int clostestIndex = 0;
    int bdistance = mDistance( start, end );

    auto push = [&]( int x, int y, int back ){
        if( x >= mapWidth || x < 0 || y >= mapHeight || y < 0 ) return;
        if( bitmap[x][y] == obstacle ) return;

//        if( visited[x][y] && step > bitmap[x][y] ) return;
        if( visited[x][y] ) return;

        const int cdistance = mDistance( Point(x,y), end );
        if( bdistance > cdistance ){
            bdistance = cdistance;
            clostestIndex = Q.size();
        }

        visited[x][y] = true;
        Q.push_back( QNode( Point(x,y), back ) );
    };

    int head = 0;
    while( head < Q.size() ){
        ++ vcount;

        const QNode current = Q[head];
        const Point cpoint = get<0>( current );

        if( cpoint == end ){
            // reconstruct path
            vector<Point> path;

            while( get<0>( Q[head] ) != start ){
                path.push_back( get<0>( Q[head] ) );
                head = get<1>( Q[head] );
            }
            return path;
        }

        push( cpoint.first + 1, cpoint.second, head );
        push( cpoint.first - 1, cpoint.second, head );
        push( cpoint.first, cpoint.second + 1, head );
        push( cpoint.first, cpoint.second - 1, head );

        ++ head;
    }
    // reconstruct path
    vector<Point> path;

    head = clostestIndex;
    while( get<0>( Q[head] ) != start ){
        path.push_back( get<0>( Q[head] ) );
        head = get<1>( Q[head] );
    }

    return path;
}


int main()
{
    mapWidth = 150;
    mapHeight = 150;

    const int ncase = 1000;
    const int nobstacle = 160;

    double totalTime = 0;
    int totalVisit = 0;
    int vc;

    for( int t = 0; t < ncase; ++ t ){
        memset( bitmap, 0, sizeof( bitmap ));
        for( int i = nobstacle; i--; ){
            bitmap[ rand() % mapWidth ][ rand() % mapHeight ] = obstacle;
        }
        bitmap[ 149 ][149 ] = 0;

        vc = 0;
        const clock_t begin_time = clock();
        auto answer = Astar( Point(0,0), Point(149, 149 ), vc );
        totalTime += double( clock() - begin_time ) / CLOCKS_PER_SEC;

        totalVisit += vc;
    }

    cout << "A star report \n";
    cout << "Average Visit : " << double(totalVisit) / ncase << endl;
    cout << "Average Time  : " << double(totalTime) / ncase << endl << endl;

    totalTime = 0;
    totalVisit = 0;

    for( int t = 0; t < ncase; ++ t ){
        memset( bitmap, 0, sizeof( bitmap ));
        for( int i = nobstacle; i--; ){
            bitmap[ rand() % mapWidth ][ rand() % mapHeight ] = obstacle;
        }
        bitmap[ 149 ][149 ] = 0;

        vc = 0;
        const clock_t begin_time = clock();
        auto answer = BFS( Point(0,0), Point(149, 149 ), vc );
        totalTime += double( clock() - begin_time ) / CLOCKS_PER_SEC;

        totalVisit += vc;
    }

    cout << "BFS report \n";
    cout << "Average Visit : " << double(totalVisit) / ncase << endl;
    cout << "Average Time  : " << double(totalTime) / ncase << endl << endl;

    return 0;
}


So I run my code but

A star report
Average Visit : 376.356
Average Time : 0.00334

BFS report
Average Visit : 22341.6
Average Time : 0.00173

A star definitely visits far less node than BFS but why it runs slower.
My guest it's a bottle neck in priority queue
but can anyone point out where the bottle neck is ?
Thanks in advance
Mar 1, 2014 at 11:44am
Did you turn on optimizations in you compiler? You might also have to make sure it doesn't optimize too much because answer is never used for anything. I think declaring answer as volatile avoids this problem.

Change the order in which you run the tests and see if that makes a difference. In my expecrience the first test is often the slowest just because it's done first. I guess it takes a while until the program gets up to speed or something ;)
Mar 1, 2014 at 11:48am
And for finding the bottlenecks I recommend using a profiler, like callgrind.
Mar 1, 2014 at 11:58am
I turned on optimization in my compiler, Yeah when I turn it off A star run at 7ms and 17ms, but shouldn't it be like 10 times faster ? but I do need them to be around 2ms.

O, O2, and O3 makes A star slower compared to BFS.

change auto to vector<Point> doesn't change much of an answer. Changing the order of the test doesn't change the speed much either..

so the problem is not within the algorithm ???
Mar 1, 2014 at 12:58pm
Gprof tells me that A* is actually way faster.

Looks like your problem is that average time is actually close to clock precision, so it will add either 0 or 1 tick every time no matter how many time is actually passed. Check what is 1/CLOCKS_PER_SEC is. You cannot have precise measurement if actual time between measurements is close to that.

Replace lines where totalTime is calculated with:
1
2
3
        const clock_t end_time = clock();
        totalTime += double( end_time - begin_time ) / CLOCKS_PER_SEC;
        cout << end_time - begin_time << ' ';

And you will see that.

Bottleneck in A* algorithm is really prioruty_queue, more precise, make_heap and adjust_heap funsctions which gets called each time when element is pushed or popped.
If A* perfomance is really is bottleneck for you, try to replace it with your own queue, using the fact that newly added nodes are more likely to be close to the back of the container. On square grid without different movement cost it will make cost of adding element amortized constant and of removing element constant. And make sure that your Node have effective move constructor to further reduce cost.
Last edited on Mar 1, 2014 at 1:18pm
Mar 1, 2014 at 1:21pm
Nope it doesn't seem to matter for my compiler..
The time doesn't change much

I am trying to say that A star should be around 10 times faster and the change can be felt by even human by their lag time.
Looking at their numbers of node visits.
based on the data I mention 376 compared to 22341 .
BFS tranverse 60 times more node than BFS
This should boost up the speed


Mar 1, 2014 at 2:01pm
I ran your program with callgrind and with default settings it also reported A* as being faster but after turning on cache and branch prediction simulation it reported A* as slower.

It reports a lot of time is spent on line 60. You don't really need to reset cameFrom each time. You never use those zero values anyway. After removing that line it runs much faster.
Mar 1, 2014 at 2:33pm
Oh yeah, I just realized that
That process takes a lot
It produces significant speed up

BFS report
Average Visit : 22341.6
Average Time : 0.00256

A star report
Average Visit : 376.701
Average Time : 0.00041

A star is 6 times faster in this case

off course on worst case BFS still wins I cannot doubt that.

Thank you everyone especially @Peter87
Topic archived. No new replies allowed.