A simple way to do compile time loop unrolling

finalpatch fengli at gmail.com
Fri May 31 07:30:35 PDT 2013


Minor improvement:

template Unroll(alias CODE, alias N, alias SEP="")
{
     static if (N == 1)
         enum Unroll = format(CODE, 0);
     else
         enum Unroll = Unroll!(CODE, N-1, SEP)~SEP~format(CODE, 
N-1);
}

So vector dot product can be unrolled like this:

mixin(Unroll!("v1[%1$d]*v2[%1$d]", 3, "+"));

which becomes: v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]

On Friday, 31 May 2013 at 14:06:19 UTC, finalpatch wrote:
> Just want to share a new way I just discovered to do loop 
> unrolling.
>
> template Unroll(alias CODE, alias N)
> {
>     static if (N == 1)
>         enum Unroll = format(CODE, 0);
>     else
>         enum Unroll = Unroll!(CODE, N-1)~format(CODE, N-1);
> }
>
> after that you can write stuff like
>
> mixin(Unroll!("v[%1$d]"~op~"=rhs.v[%1$d];", 3));
>
> and it gets expanded to
>
> v[0]+=rhs.v[0];v[1]+=rhs.v[1];v[2]+=rhs.v[2];
>
> I find this method simpler than with foreach() and a tuple 
> range, and also faster because it's identical to hand unrolling.



More information about the Digitalmars-d mailing list