Optimize my code =)
Chris Cain
clcain at uncg.edu
Fri Feb 14 09:18:52 PST 2014
On Friday, 14 February 2014 at 16:00:09 UTC, Robin wrote:
> This is my class with its templated data as a one dimensional
> array (as I don't like jagged-arrays) and a dimension (which is
> a struct). The dimension object has some util functionality
> such as getting the total size or mapping (row, col) to a
> one-dimensional index besides the getter for rows and columns.
Are you sure you need a class here? If you're not using
inheritance, structs can be much faster.
> this(size_t rows, size_t cols) {
> this.dim = Dimension(rows, cols);
> this.data = new T[this.dim.size];
> enum nil = to!T(0);
> foreach(ref T element; this.data) element = nil;
> }
You don't need to use std.conv.to here (ditto for when you
initialize sum later). This should work and is clearer:
foreach(ref T element; this.data) element = 0;
(You can do `double item = 0;` and it knows enough to store the
double equivalent of 0)
In the case of initializing sum, I'm not sure the compiler is
folding `sum = to!T(0);` thus you could be getting a lot of
overhead from that. Using std.conv.to is fine but it does
actually do checks in the conversion process, so it can be
expensive in tight loops. Since you're just using a constant 0
here, there's no reason to use std.conv.to.
> The function I am mainly benchmarking is the simple matrix
> multiplication where one of the multiplied matrices is
> tranposed first in order to improve cache hit ratio.
Did you benchmark first to make sure this actually improves
performance? It seems to me like doing the transpose would
require the same cache-missing that you'd get in the actual use.
If you were caching it and using it multiple times, this would
probably be more beneficial. General tip for optimizing:
benchmark before and after every "optimization" you do. I've been
surprised to find some of my ideas for optimizations slowed
things down before.
> Another nice thing to know would be if it is possible to
> initialize an array before it is default initialized with
> T.init where T is the type of the array's fields.
http://dlang.org/phobos/std_array.html#.uninitializedArray
More information about the Digitalmars-d-learn
mailing list