# HG changeset patch # User maedhros # Date 1181686429 0 # Node ID 6f2927f456d70c7ee7603c518d298cab1badb2d9 # Parent 5cefd3ac59c7a2b521d01c065cbf8de18cf63baf (svn r10122) -Codechange: Add a CountBitsSet function and use it to replace some less efficient loops. diff -r 5cefd3ac59c7 -r 6f2927f456d7 src/economy.cpp --- a/src/economy.cpp Tue Jun 12 20:24:12 2007 +0000 +++ b/src/economy.cpp Tue Jun 12 22:13:49 2007 +0000 @@ -67,10 +67,7 @@ uint num = 0; FOR_ALL_STATIONS(st) { - if (st->owner == owner) { - uint facil = st->facilities; - do num += (facil&1); while (facil >>= 1); - } + if (st->owner == owner) num += CountBitsSet(st->facilities); } value = num * _price.station_value * 25; @@ -144,10 +141,7 @@ const Station* st; FOR_ALL_STATIONS(st) { - if (st->owner == owner) { - int facil = st->facilities; - do num += facil&1; while (facil>>=1); - } + if (st->owner == owner) num += CountBitsSet(st->facilities); } _score_part[owner][SCORE_STATIONS] = num; } @@ -196,9 +190,7 @@ /* Generate score for variety of cargo */ { - uint cargo = p->cargo_types; - uint num = 0; - do num += cargo&1; while (cargo>>=1); + uint num = CountBitsSet(p->cargo_types); _score_part[owner][SCORE_CARGO] = num; if (update) p->cargo_types = 0; } diff -r 5cefd3ac59c7 -r 6f2927f456d7 src/functions.h --- a/src/functions.h Tue Jun 12 20:24:12 2007 +0000 +++ b/src/functions.h Tue Jun 12 22:13:49 2007 +0000 @@ -147,8 +147,10 @@ void ChangeTownRating(Town *t, int add, int max); uint GetTownRadiusGroup(const Town* t, TileIndex tile); +void ShowHighscoreTable(int difficulty, int8 rank); + int FindFirstBit(uint32 x); -void ShowHighscoreTable(int difficulty, int8 rank); +int CountBitsSet(uint32 value); void AfterLoadTown(); void UpdatePatches(); diff -r 5cefd3ac59c7 -r 6f2927f456d7 src/misc.cpp --- a/src/misc.cpp Tue Jun 12 20:24:12 2007 +0000 +++ b/src/misc.cpp Tue Jun 12 22:13:49 2007 +0000 @@ -270,6 +270,21 @@ return i; } +int CountBitsSet(uint32 value) +{ + int num; + + /* This loop is only called once for every bit set by clearing the lowest + * bit in each loop. The number of bits is therefore equal to the number of + * times the loop was called. It was found at the following website: + * http://graphics.stanford.edu/~seander/bithacks.html */ + + for (num = 0; value != 0; num++) { + value &= value - 1; + } + + return num; +} static void Save_NAME() { diff -r 5cefd3ac59c7 -r 6f2927f456d7 src/roadveh_cmd.cpp --- a/src/roadveh_cmd.cpp Tue Jun 12 20:24:12 2007 +0000 +++ b/src/roadveh_cmd.cpp Tue Jun 12 22:13:49 2007 +0000 @@ -1085,15 +1085,8 @@ static int PickRandomBit(uint bits) { - uint num = 0; - uint b = bits; uint i; - - do { - if (b & 1) num++; - } while (b >>= 1); - - num = RandomRange(num); + uint num = RandomRange(CountBitsSet(bits)); for (i = 0; !(bits & 1) || (int)--num >= 0; bits >>= 1, i++) {} return i;