Hi all. I'm back at it now that its cold outside :). I'm working on a little 3d library to do a game. I've been using a 500 face teapot .ASC mesh as my benchmark for speed. Flat shaded, I am doing about 26FPS right now with 1 dynamic light source on my Maestro. And I've got a long way to go.
So before about an hour ago, the damn thing was running at about 13FPS. I doubled the speed by eliminating two lines of code!
- Code:
memset(left, 0, nScreenHeight * sizeof(EDGE_INDEX));
memset(right, 0, nScreenHeight * sizeof(EDGE_INDEX));
These are my two edgelists used in polygon rasterization. Fortunately, setting them to 0 for every polygon drawn isn't necessary. But why would it be THAT slow?
My EDGE_INDEX struct looks like so:
- Code:
typedef long fixed;
struct EDGE_INDEX
{
fixed x;
fixed r, fixed g, fixed b;
};
They are allocated when my library is initialized as so:
- Code:
left = new EDGE_INDEX[nScreenHeight];
right = new EDGE_INDEX[nScreenHeight];
So are memsets really this slow?! Is there anything I can do to speed them up? I searched for "memset" here and found a few discussions on clearing memory, but it seems memset was deemed fastest... There are indeed times where I really do need to clear some buffers, so I guess this information is important to me.
Also, earlier this year, I was even stupider, allocating "large" amounts of memory and deallocating for each frame and polygon drawn. Blech, wow did I learn. My question is, does HeapAlloc do anything better than new? Does HeapAlloc guarantee fragment-free memory?
I guess I need someone to give me some pointers on tricks of keeping memory access quick. I appreciate it. But damn, I'm happy I doubled the speed. I want to triple that now :). Happy coding.
Chris
Sometimes you can get a real performance boost by creating a separate heap and use HeapAlloc and so forth, but if don't create a separate heap I see no reason to use HeapAlloc.
I don't know if this is applicable in your 3D engine, the only times I have used a separate heap has been when working with large texts.
I guess you will get some good answers by Refractor or someone else soon so I'll just shut up now!
some good answers by Refractor
Thanks, nice to be appreciated

- I'll give it a shot.
In a hurry, so these are just notes, really... :
But why would it be THAT slow?
It's because your cache hates you.
Your write-buffer does too. My guess would be because you'd be thrashing the cache.
If you say screen-height is 240, then you're potentially dumping 16*240*2 = 7.5KB through memory. Yuck.
You'd probably have found it faster to clear each structure individually (at least the X) just before you use it - that gets it into the cache just when you need it there...
- Memset tends to be fairly well optimised, for obvious reasons. You could claw a bit of performance back by making a routine in assembler; even with my penchant for assembler, I wouldn't bother.
- Bundling the X,R,G,B into a structure makes it "nice" code-wise, but makes a whole lot less sense cache-wise.
Your data is organised like this:
XRGBXRGBXRGBXRGB..etc
Your memset is/was having to set a whole load of data that it simply (depends on the rest of your setup) doesn't need to (you really need to reset the colours to black between polys?).
Try reorganising it like this:
- Code:
struct EDGE_COLOUR
{
fixed r,g,b; // NB: You really need 32 bits per component?
}
...
left = new fixed[nScreenHeight];
right = new fixed[nScreenHeight];
leftColours= new EDGE_COLOUR[nScreenHeight];
rightColours= new EDGE_COLOUR[nScreenHeight];
This leaves your data organised as:
XXXXXXXXXXXXXXXXXXXXXXXXXXX... x 2
RGBRGBRGBRGBRGBRGBRGBRGBRGB...
So, when/(if!) you clear/read the left/right, you're then clearing contiguous values (which uses the write-buffer and cache effectively).
- As noted in the code above, if you don't need the 32bits per component, don't have it all - chop it down to a 16-bit maybe. You may lose a bit of performance with a "bad" compiler, but you'll gain on the caching aspect.
My question is, does HeapAlloc do anything better than new? Does HeapAlloc guarantee fragment-free memory?
I wouldn't see fragmentation as your problem - the use of the cache/buffer is, however.
The main "trick" is to optimise your data-structures to make use of the way that they're used. If you're using the X components in one processing step, then using the RGBs in another, you don't want the data mixed in together. The other obvious thing to do is make the data-structures only as big as they have to be.
HTH,
Ref
The main "trick" is to optimise your data-structures to make use of the way that they're used. If you're using the X components in one processing step, then using the RGBs in another, you don't want the data mixed in together. The other obvious thing to do is make the data-structures only as big as they have to be.
HTH,
Ref
Damn, this will probably be one of the most important things I walk away with (the structure setup based on use) :). Thanks so much everybody. Ugh. I don't feel like being at work now creating weather imagery... I want to be at home optimizing!!! :lol:
Chris
FYI, malloc, opeartor new, LocalAlloc, etc. all use HeapAlloc under the hood. I've used private heaps before to store allocations per level of my game, then destroyed/recreated the heap when I went to a new level. This was done to eliminate heap fragmentation introduced by previous versions of CE's heap manager. Things might have gotten better with Windows Mobile 2003 though.
You might want to consider getting rid of the edge arrays altogether and just scan convert during your edge stepping routine.
This topic should be made a "sticky". As a "old-school" ASM programmer, I forget how people look at their data... ie; they look at it from their perspective, not the hardware's. I've tried to explain this to other people at times, but I don't think I ever got the point across. Refractor's answers to DooMer_MP3's example is probably the best example I've ever seen of this. A nice simple case where not using the cache correctly can just absolutely kill your performance, and a simple change can get you a 2x increase. I've reorganized massive data arrays into tiles and seen a 10x improvement. When your CPU speed is 4x faster than your memory... the cache makes a big, big difference.
Cheers,
rcp
rcp,
Can you give a quick example of the original array you were dealing with, and an example of what you did to get it in "tile" form? I'm not quite understanding you here. I appreciate it though. But yes, this information seems REAL important.
Chris
Chris,
I'll try to make this as simple as possible. In doing so, I am most likely going to get something wrong... so please take this as a 'high level' view and get the facts from real documents. I might suggest the Intel XScale Optimization guide as a starting point.
Recently, I was working on a voxel landscape. Just to get started, I put together a 256x256 height map. Things looked good. I made it a little bigger, then bigger, and so on until it was 4096x4096. That is 16MB, which obviously is going to cause some trouble. A voxel engine "looks" out from the viewpoint into the height map. Whilst doing so, it is in a sense 'walking' through the memory. If you look in one direction, you might be 'walking' through the memory in order, so after the first miss, the rest of your reads (for a while) come from the cache. However, if you are looking in another direction, each height sample might be a long way away from the last one, thus all you get is cache misses. Thus as I rotated my landscape I would get 25 fps when looking in one direction and 2fps when looking in another. By re-arranging the height map in 'tiles' you can minimize this problem. I'll try to illustrate here...
Say this is a height map and the numbers illustrate the offest from the beginning of the buffer. Each 'row' of height data is 8 bytes long.
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
etc. etc.
Lets say that your cache is only 8 bytes deep. If you are walking from left to right, then there is no problem, as the first read is a miss, but the next 7 come from the cache. If you are walking from top down, however, all reads will be a miss. The issue here is the 'pitch' of your data. That is, the number of byte from one row to the next.
(BTW, this 'pitch' problem is why a lot of games and movie players slow down so much when you try to run them in portrait or landscape mode and the display memory is not organized in the same mode. There are simple methods to overcome this, but for some reason they don't always get implemented)
If you re-arrange your array as 'tiles' this can be fixed. Using a 'tile' (of 2x2 in this example) reduces the 'pitch' of your data, making successive rows live closer together.
0 1 4 5 8 9 12 13
2 3 6 7 10 11 14 15
15 16 18 19 22 23 26 27
16 17 20 21 24 25 28 29
etc. etc.
now when you walk down, you at least get a free read. This is just a simple example, in reality you would make your tiles much bigger, generally about the size of one cache 'line'. Most caches have multiple 'lines', and each 'miss' loads a new 'line' of data. Then, hopefully, the next reads come from that cache 'line'. If the next read doesn't come from the cache, the 'line' is still kept around for awhile in case one of the next reads comes from that. Thus you need to keep in mind how the cache is arranged (how many lines and how big each line is) such that you can be reading from several different locations and have them all comming out of the cache.
This brings up another problem of reading from one more area than you have cache lines for, thus bumping the last used line out of the cache, but then reading from that area again, causing the cache to reload. (thrashing is one term for this, although it can be used differently). Thus you might find a big speed up by reading from one less buffer. One of the things I try to do (as Refractor suggested) is to minimize what you put in a structure when you are using an array. For example, lets say you have 8 arrays of structures you are working with. Each structure entry holds 64 bytes. Maybe you are accessing them in a somewhat linear fashion (thus a possiblity for cache hits). One cache line of 1024 bytes would hold 16 entries. Lets say you have a 8K cache arranged as 8 lines of 1024 bytes. Now, if you are walking through your arrays such that you are not skipping more than 16 entries, you will be using you cache very effeciently. However, if you are skipping around a little, then you might be seeing a lot of cache misses. Maybe one array is being accessed in a 'good way' so it can fit in the cache. However, the other arrays are not, and after they cause 7 misses, the 'good array' gets bumped from the cache. So even though it is a good candidate, it gets lost. You might just be screwed, but sometimes you can look at the data in the structures and see that 50% or more of the data is seldom used. Important data... but not used all the time. If you put this data in another array, then you can reduce the size of the arrays you are continuously working with. Thus you might find that with a few changes your critical data stays in the cache. If the above example structure above had only 8 bytes that were used a lot and you could break out and store the other 56 byte entries in another array, then you can fit 8 times the entries in one cache line. This might make the critical difference in keeping data 'in cache'. This can be really important because you can get into situations where one little cache miss can cause a cascade effect. Example; 8 lines are cached, you read from somewhere else, line 0 is lost to get the new data. You then read from where line 0 used to be cached, but it is gone and thus you get a 'miss' which then bumps line 1. Then you read from where line 1 was... and now line 2 gets bumped...and so on. If you changed your array sizes or number of arrays you were reading from, you might be able to avoid this cascade effect. Thus one small change to a data structure could have a huge impact on the speed.
I try to picture (actually, I like to draw pictures) of the cache and where my data is living during sections of code that are speed critical. You should design your algorithms such that they best fit the cache arrangement on the processor. A lot of times a good algorithm design (from a human perspective) can suck from a processor cache perspective. Both your algorithms and your data structures need to be designed to work with the processor's cache. The resulting code may look strange to you, but what really counts is how it looks to the processor.
Just remember... "keep your data close and don't branch!"
Cheers,
rcp
Good job rcp.
There's more on caching in <a href="http://www.pocketmatrix.com/forums/viewtopic.php?t=10614">this thread</a>.
When I finally get my new server and the "demo site" up, I/we are planning some articles on optimisations like these.

Yep, I had the same experience with tiling in my voxel engine. Before the tiling depending on how the heightmap/texturemap were being sampled the performane increased or decreased. Using tiling makes sure you have a constant performance.
some sample code to create a tiled version from your texture (example for 16x16 tiles, too big for the arm cache, but just to give you an idea):
- Code:
for (u=0; u<512; u++) {
for (v=0; v<512; v++) {
int dst = (u & 0xF) + ((u & 0x1F0) << 9) + (v << 4);
tiledTexture[dst] = TextureBuffer[v*512+u];
}
}
and to calculate the offset for a given x,y into the tiled buffer use:
- Code:
int offset = (x & 0xF) + ((x & 0x1F0) << 9) + (y << 4);
there's a good article on those kind of optimizations the fatmap.txt file, check it out at:
http://sunsite.lanet.lv/ftp/mirror/x2ftp/msdos/programming/theory/fatmap.txt
The article is quite interesting, but when i implemented the texture tiling in my texture mapper it didn't seem to affect the performance at all.
But anyway there's nice information about texture mapping in the doc although there is a newer version called fatmap2.txt...
Wow you guys rock. Thanks so much. Implementing all of these optimizations have been quite fun. I'll keep you posted on what I come up with.
Chris