|
Suggestions for optimization |
StanEd
Member #16,038
August 2015
|
Hi guys, I just needed an 'is_same_bitmap' function (compares only the image data of the bitmap and ignores alpha [suitable for the purpose I had in mind]) I wrote the following which when using memory bitmaps is perfectly fast for my purposes (it's a one off conversion job rather than a critical run-time process) but I'm always keen to know of improvements I can make to code. So, here is my code and I'd welcome any suggestions for optimization or how you might write the same function. 1bool al_is_same_bitmap(ALLEGRO_BITMAP *img1, ALLEGRO_BITMAP *img2)
2{
3 if(al_get_bitmap_width(img1) != al_get_bitmap_width(img2) ||
4 al_get_bitmap_height(img1) != al_get_bitmap_height(img2))
5 {
6 // Simple check, if they are not the same size they can't be the same.
7 return false;
8 }
9
10 int x;
11 int y;
12 ALLEGRO_COLOR colour1;
13 ALLEGRO_COLOR colour2;
14 unsigned char r[2];
15 unsigned char g[2];
16 unsigned char b[2];
17
18 for(y = 0; y < al_get_bitmap_height(img1); y += 1)
19 {
20 for(x = 0; x < al_get_bitmap_width(img1); x += 1)
21 {
22 colour1 = al_get_pixel(img1, x, y);
23 al_unmap_rgb(colour1, &r[0], &g[0], &b[0]);
24 colour2 = al_get_pixel(img2, x, y);
25 al_unmap_rgb(colour2, &r[1], &g[1], &b[1]);
26 if(r[0] != r[1] || g[0] != g[1] || b[0] != b[1])
27 {
28 return false;
29 }
30 }
31 }
32 return true;
33}
Thank you, Stan |
SiegeLord
Member #7,827
October 2006
|
You can speed things up by locking the bitmaps. Also, if you do lock them you can compare them line-by-line like so: 1ALLEGRO_LOCKED_REGION *lr1 = al_lock_bitmap(b1, al_get_bitmap_format(b1), ALLEGRO_LOCK_READONLY);
2ALLEGRO_LOCKED_REGION *lr2 = al_lock_bitmap(b2, al_get_bitmap_format(b1), ALLEGRO_LOCK_READONLY);
3
4for (int y = 0; y < al_get_bitmap_height(b1); y++) {
5 if (memcmp((char*)lr1->data + lr1->pitch * y,
6 (char*)lr2->data + lr2->pitch * y,
7 lr1->pixel_size * al_get_bitmap_width(b1)) != 0) {
8 al_unlock_bitmap(b1);
9 al_unlock_bitmap(b2);
10 return false;
11 }
12}
13
14al_unlock_bitmap(b1);
15al_unlock_bitmap(b2);
16
17return true;
"For in much wisdom is much grief: and he that increases knowledge increases sorrow."-Ecclesiastes 1:18 |
Chris Katko
Member #1,881
January 2002
|
How often do you do this twice? That is, the same bitmap will be checked twice? And how often are the bitmaps changed? Because it might be useful to just calculate hashes for them (going pixel by pixel once per bitmap) and then compare the hashes. -----sig: |
|