PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

pointers and arrays! More Speeeeeeeed!

Hi all, just a few Q's

what is faster?

Code:

void place_screen_transA(PIXEL *src, PIXEL *dest, int transcolor)
{
int calc;
for (int y = 0; y < 320; y++)
{
for (int x = 0; x < 240; x++)
{
calc = x + (y * 240);
if (src[calc] != transcolor)
dest[calc] = (src[calc] ^ dest[calc]);
}
}
}


or

Code:

void place_screen_transA(PIXEL *src, PIXEL *dest, int transcolor)
{
int calc;
for (int y = 0; y < 320; y++)
{
for (int x = 0; x < 240; x++)
{
calc = x + (y * 240);
if (*(src + calc) != transcolor)
*(dest + calc) = *(src + calc) ^ *(dest + calc));
}
}
}


if option B is faster, how would one reference an array defined as int fred[5][5] etc
The above example is a bad example, because it can be done all sequentually etc, but I have others that copy sub sections, hence the required x and y...

here is a better example:
Code:

void place_screen_transA(PIXEL *src, PIXEL *dest, int transcolor)
{
for (int y = 0; y < 76800; y++)
{
if (src[y] != transcolor)
dest[y] = (src[y] ^ dest[y]);
}
}




-B
Arrays and pointers are basically the same thing in C. So *(dest+calc) or dest[calc] is more or less a question of syntax and will compile into the same code.

Refering to the example array fred would be done like this fred[5*y+x]. When arrays have more than 1 dimension they become a little bit more different from pointers. Doing fred[5*y+x] is by no means faster than fred[y][x].

When it comes to optimisation the key is to know what things cost cycles. On todays CPUs this is among other things:

* branches, jumps
* reads/writes of memory
* multiplys/divides

These things are the most relevant to your examples.

For example, the loops involve taking many iterations and each iteration requires a branch.

You do many reads and writes of memory.

If you write code a certain way you will do many multiplications.

Some of these things are optimized by good compilers but other things are not. For example, many compilers don't do read/write combining. Reading/writing an 8 or 16-bit value basically costs just as much as reading a 32-bit value so if you need to read consecutive values that are smaller than 32-bits it makes sense to combine them.

For example, if your PIXEL type is sixteen bits you could rewrite your last example as

Code:

void place_screen_transA(PIXEL *src, PIXEL *dest, int transcolor)
{
for (int y = 0; y < 76800; y+=2)
{
int twosrcpix = *((int *)(src+y));
int twodstpix = *((int *)(dest+y));
PIXEL a = twosrcpix & 0xffff;
if (a != transcolor)
a = a ^ (twodstpix & 0xffff);
PIXEL b = twosrcpix >> 16;
if (b != transcolor)
b = b ^ (twodstpix >> 16);

twodstpix = b;
twodstpix << 16;
twodstpix |= a;

*((int *)(dest+y)) = twodstpix;
}
}


NOTE: There's very likely something wrong with my example code but it illustrates the general idea.
What Opre said is true that dest + y is equivalent to dest[y], in that the memory location to access will be stored at location y, but its still indirection and you can completely remove all of those except the first in most cases.
In other words you find the memory location then dereference that location to get the value stored there. You can cut out the indirection down to one per array, and then use ++ to step thru the array, then you only need the dereferece for each access. This can also potentially put any memory cache in better position for future accesses, since you will be sequentially going thru memory in a large block.

Code:

void place_screen_transA(PIXEL *src, PIXEL *dest, int transcolor)
{
PIXEL * psrc = src;
PIXEL * pdst = dest;
for (int y = 0; y < 76800; y++, psrc++, pdst++)
{
if (*psrc != transcolor)
*pdst = (*psrc ^ *pdst);
}
}


I'm pretty sure XOR isn't transitive (is that the word?) so *pdst ^= *psrc will work as well. But thats an easy optimization that your compiler may already do. Check the listings to be sure.

And finally, try to inline this directly or with keywords. The function call is pretty expensive for inner loops. Case in point when calling that function you create the pointers src and dest, and then my code creates them again. You could of course use them directly (ie change psrc to just src, and pdst to dest), and that should clue you in to some of the costs with calling a function.


brendan wrote:
Code:

void place_screen_transA(PIXEL *src, PIXEL *dest, int transcolor)
{
for (int y = 0; y < 76800; y++)
{
if (src[y] != transcolor)
dest[y] = (src[y] ^ dest[y]);
}
}

I guess the PIXEL is a 16 bit int? If that is the case you could do what Orpe suggested, but you can still cut out a lot of redundancy.

Code:

void place_screen_transA(PIXEL *src, PIXEL *dest, int tranlow)
{
int * psrc = (int *)src;
int * pdst = (int *)dest;

int tranhigh = tranlow << 16;

for (int y = 0; y < 76800; y += 2, psrc++, pdst++)
{
if((*psrc & 0xFFFF) != tranlow)
*pdst ^= *psrc & 0xFFFF;

if((*psrc & 0xFFFF0000) != tranhigh)
*pdst ^= *psrc & 0xFFFF0000;
}
}



What Opre suggested is dependant on PIXEL being 16 bit, but its a fairly common optimization for blitting images, you do larger batches with smaller bit sizes of course.

This can be seen in similar light to loop-unrolling, which also potentially gains speed at the cost of size, and example of that is:

Code:

void place_screen_transA(PIXEL *src, PIXEL *dest, int tranlow)
{
int * psrc = (int *)src;
int * pdst = (int *)dest;

int tranhigh = tranlow << 16;

for (int y = 0; y < 76800; y += 4, psrc++, pdst++)
{
if((*psrc & 0xFFFF) != tranlow)
*pdst ^= *psrc & 0xFFFF;

if((*psrc & 0xFFFF0000) != tranhigh)
*pdst ^= *psrc & 0xFFFF0000;

psrc++;
pdst++;

if((*psrc & 0xFFFF) != tranlow)
*pdst ^= *psrc & 0xFFFF;

if((*psrc & 0xFFFF0000) != tranhigh)
*pdst ^= *psrc & 0xFFFF0000;
}
}



Of course you can do this for the entire loop, however in this case: 76800 is a very large number. The best gain will be for unrolling to two. In this case whatever the cost of the loop, you've reduced it by half for the function.


Anyway, I have a golden rule for doing this sort of things. Check your compiler generated listings, no sense doing work that the compiler can already do for you. Generate the code before and after and compare it, this is even more helpful than actually running timing tests, since you can look at the instructions that will be performed. Even if you don't know assembly, get the compiler to comment the listings with your code and all you have to do is find sections, if its the same then you optimization was done before you tried to add it in code.
Code:
int tranhigh = tranlow << 16;


You want unsigned or it won't work properly.

This is the kind of function that's surprisingly easy to do in ARM assembler. :)
1.instead the ugly

for(i-0;i<1000;i++)
{
}
use

i=1000
while(i-->0)
{
}
better performace

2.
Another thing is about transparent color.. like was said dozens of times here you really need a nice "RLE encoding" of alpha channel (no matter if it's 1bit like in your example or >1bit)

Advantages:
-MUCH faster (on PC with if statement transparent bitmap copy was about 3x slower then normal bitmap copy... with RLE coded transparent information your transparent bitmap copy can be EASILY MUCH FASTER then normal bitmap copy. It all depends how many pixels of your bitmap are transparent.. and a 1pixel transparent/non-transparent grid would be a bad test bitmap :-)
-saves space on disk, lots of it (you don't need to keep 16bpp for transparent pixels, you do get some additional data saved thru, but it's most often much smaller)

disadvantages:
-harder to code.. especially with clipping and you need some additional code to preprocess bitmap...but it's well worth it:-)

So this alpha-RLE encoding works pretty much like this:
I - PREPROCESSING
1.we have got a WORD that keeps info about number of pixels ahead that are transparent (one byte-lets say lower8bits) and number of pixels that are non-transparent ie. solid:-) (also one bit-high 8bits of WORD)
2.After this word you place x pixels data, where x is number of solid pixels ahead
3.repeat for whole image

II-DRAWING
1.we read our WORD with info about nr of transparent pixels ahead and number of solid pixels after them
2.we change dst pointer position by number of transparent pixels
3.we draw number of solid pixels stored in the other 8bits of info from WORD
4.repeat as long as data is expected and/or we're not at the end of line (or end of screen if clipping is used)

So from this scheme it's obvious that you don't use tons of if instructions in your drawing loop... what's equally important is that you don't keep reading data which appears to be a transparent pixel and waste a lot of time this way.

Here's a small example:

0-transparent pixel
1-solid pixel (later represented as normal 16bpp data)

0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0

we have a simply image (only alpha bits present here)
now we use the above scheme to preprocess image and we get this data: (saved word after word)

0x0402 - first control word (lower 8 bits - transparent pixels, higher 8 bits - solid pixels)

0x0001 - first pixel color

0x0001 - second pixel color

0x0001 - third pixel color

0x0001 - fourth pixel color

0x0404 - second control word

0x0001 - first pixel color(of course first pixel in this control word)

0x0001 - second pixel color

0x0001 - third pixel color

0x0001 - fourth pixel color

0x0002 - third ans last control word - only transparent pixels

first obvious thing, from 16 pixels (16bpp each) we dropped to 11 (16bpp) variables (8 from those are pixel color values) - so we save some memory, and this example is far from good for our method (in most sprites you will notice 10+pixels of the same type one after another)

now when drawing you don't need to perform an if on each pixel, and blocks of transparent pixels are processed WITH ONE ADD INSTRUCTION! (you simly incresae the destination pointer by number of transparent images, nothing more)


To check if we have reached end of sprite line and we need to go down one line I check control word for 0x0000 (so 0 transparent and 0 solid pixels ahead), it's obvious that in normal situation this combination isn't possible, so I use it to make my drawing function aware that we're at the end of a line(or possibly even end of bitmap).
Of course you need to make your preprocessing function add those 0x0000 at end of every line. It costs you 2 additional bytes per line but it's well worth to use instead trying to keep track of which pixel you're drawing in line.




Ok, I have got enought for now :-)
For example source I think that phantom's ball-sprite example (the one that drawed tons of balls) uses it together with c-buffer, so you might want to check it out.

If you need some more example source I have got a simply ddraw function in 80x86 asm on my hd including preprocessing (it automatically performs preprocessing while loading .tga image)
MirekCz wrote:
1.instead the ugly

for(i-0;i<1000;i++)
{
}
use

i=1000
while(i-->0)
{
}
better performace


Why? just curious?

Ok, the above example was a really bad one etc, here is a real example I actually use:
Code:

void place_item(int destsizex, int xpos, int ypos, int xsize, int ysize, int number_itemsx, int item, PIXEL* src, PIXEL* dest)
{
unsigned int dest_loc = (destsizex * ypos) + xpos;
unsigned int source_width = number_itemsx * xsize;
unsigned int source_loc = ((item / number_itemsx) * source_width * ysize) + //y offset
((item % number_itemsx) * xsize); //x offset

if ((xpos+xsize < 0) || (xpos >= 240) || (ypos+ysize < 0) || (ypos >= 320))
{
//not even on the screen
}
else
{
for (int y = 0; y < ysize; y++)
{
if ((y+ypos < 320) && (y+ypos >= 0))
{
for (int x = 0; x < xsize; x++)
{
if ((x+xpos < 240) && (x+xpos >= 0)) dest[dest_loc + x] = src[source_loc + x];
}
}
dest_loc += destsizex; // move down a row in dest
source_loc += source_width; // move down a row in source
}
}
}


now I know it's very un-optimised, and with the <320 / <240 tests it slows it down a bit, and really should be re-written so it does not need to test....

what it does is copy a "tile" smaller area from a larger buffer to the destination buffer.

anyhow so what your saying is it would be faster with while loops?
brendan":2t3af0rz]



It is slightly more efficient on most architectures to test something against 0. However, the difference is very very small and can be neglected except in extreme cases s.a. a very tight inner loop with many iterations. You could basically save a few cycles per iteration, but with a good compiler there will basically be no difference.

As for what is ugly... I have to say that i prefer the for loop variant since it improves readability and avoids a "dangling" statement just before the loop which can easily get lost etc when you restructure the code.

The key, as always, is to optimise where you actually gain something. Changing for loops to while will not help you much compared to the other optimisations you should do first.
The test against zero is faster but that has nothing to do with the while loop, any loop can be reversed to test against zero. Like Orpe said the dangling loop init can cause problems, and in most cases the step can also get lost with a while, whereas the for loop both of those in addition to the test are always in the same spot, usually. So its much easier to debug and also less likely to cause bugs.

Of course thats just when you use a good coding style you can get the same bad effects that while has by doing this:
Code:

i = 1000;
for(;--i;)
{
}


As for your code Brendan, there are a few things that you can do to improve it, one is to reduce the number of parameters. If this is something you do during a draw, and or something you do alot (call this function) reducing the number of parameters can really help. Secondly there is a thing called a loop invariant, this is something within the loop that doesn't change, you can remove it from the loop. There are a number of things you can do this for. As was mentioned above the array indirection, (ie array[x]). You can get a pointer to the start of the line for the inner loop and then step thru each line with a pointer.

You can make this function simpler, and do some of those calculations on the parameters before you call it and cut down the number of parameters you send. Its very sloppy, and I don't want to figure out what you are trying to do, also the function could be named better. ;)

Some other potential tips, you could maybe use memcpy or the like for your scanline. SInce you are not doing anything but a raw copy this should be possible.
You can maybe precalculate your "bounds" so you can remove the test in each of your loops and bring them out one level. So the Y test will be outside the Y loop and the X test will be outside the X loop.

Code:

dest[dest_loc + x] = src[source_loc + x];

This is the loop invariant I was speaking of, you know where dest[0] and src[0] are, get a pointer to that and then step thru, while this may not look like an expression (ie array[0]) it is, and it has its costs.
Code:

*pdst++ = *psrc++;

This is much cheaper than the above. However,
Code:

memcpy(pdst, psrc, xsize);


Is potentially cheaper still. Especially if memcpy can copy larger blocks.