I spent the past hour trying to optimize a block of code I wrote that renders a simple coloured line directly to a backbuffer.
I've compared it with one of the DrawLine
method implementations of the WriteableBitmapEx project, and found that my algorithm isn't quite as fast (unless I use Parallel
).
public static unsafe void DrawLineVector(this IntPtr target, Line2D line, int colour, int width, int height)
{
var buf = (int*) target;
var start = line.Start;
var lineVector = line.Stop - start;
var steps = (int)lineVector.Magnitude();
var uX = lineVector.X / steps;
var uY = lineVector.Y / steps;
var col = colour;
Parallel.For(0, steps, i =>
//for (var i = 0; i != steps; ++i)
{
var x = start.X + uX * i;
var y = start.Y + uY * i;
if (x > -1 && y > -1 && x < width && y < height)
buf[(int)y * width + (int)x] = col;
//x += uX;
//y += uY;
}
);
}
Note, the Line2D
object is basically just a container for two VectorD
objects (which are my own implementation of vectors).
Running this as it is currently, will get me, on my machine, roughly 300MPixels per second, while the "default" DrawLine
method fromWriteableBitmapEx gets me around 170MPixels per second. If I use the 'serial' version of this (i.e. not use
Parallel`), I get around 100MPixels per second.
Is there any way I can optimize this further?