I just have to point out this little snippet because it's one of those rare it just works experiences when you can solve a complex problem with a single line of code.
I'm toying with some ray tracing code, one of the classic hackers playgrounds. Ray traced images can take a long time to render and I have a pretty modern machine so I wanted to make best use of my dual CPUs. I began with a loop that looked like this:
for(int x = 0; x < bitmap.Width; x++)
{
RenderLine(x);
}
While the rendering is in progress you can see the image gradually filled in from left to right. Pretty simple but writing the code to divide the loop up into sensible pieces and distribute it to a pool of threads was going to be more work than the actual ray tracing itself. Fortunately I happened upon the Parallel Extensions library which let me implement all of the above by referencing a .dll and changing a single line of code:
Parallel.For(0, bitmap.Width, (x) =>
Now that's magic. Rather than rendering the image one line at a time the library has decided that 4 threads would be optimal for my dual CPU configuration and chunked the work accordingly. The image below is taken part way through a render and shows that the loop has been broken into segments of about 20 pixels each:
Now I have more time to spend sorting out the horrible colours on that sphere! There are a couple of things I should mention before closing:
There is a good amount of advice in the documentation that comes with the library and a number of articles online if you want to know more.
Labels: Parallel Extensions, Ray Tracing