Obviously I don't know your actual intent, but I question the assumption that "the real scenario where I want to use this concept may result in some advantage."
It may not be 100% accurate to say that humans can no longer write efficient assembler for i386, but it's nearly true. If you are familiar with pipelining and out-of-order execution, you already understand why this is so. If you aren't familiar with these, you are already saying you don't know how to write efficient assembler.
That's not to say you shouldn't look at the assembler for your program's hotspots. But you should write the most efficient c code you can and benchmark it before trying to see if you can write something better in asm. Don't be surprised if you can't.
- Remember that just because some tiny routine performs better in a tiny test program, that doesn't guarantee that it will do so when included back in the original program.
- Or that it will perform better on all processors.
- Or in new versions of the compiler.
- And of course using asm means that moving to new platforms (like x64) will probably require the asm to get re-written, causing the people doing the work to curse your name.
That said, you could try benchmarking something like this. My guess is that it will be better, but that's just a guess.
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#define MAXTOT 5
typedef unsigned char BYTE;
int main()
{
BYTE *buffer = (BYTE *)malloc(MAXSIZE);
const BYTE *start = buffer;
unsigned int t0, t1, t2, t3, t4;
for (int i = 0; i < MAXSIZE; i++)
buffer[i] = i;
t0 = 0;
t1 = 0;
t2 = 0;
t3 = 0;
t4 = 0;
for (int j=0; j < (MAXSIZE / MAXTOT); j++)
{
t0 += start[0];
t1 += start[1];
t2 += start[2];
t3 += start[3];
t4 += start[4];
start += MAXTOT;
}
printf("%u %u %u %u %u\n", t0, t1, t2, t3, t4);
free(buffer);
return 0;
}
The loop looks like this in asm (using gcc -O2):
L3:
movzbl (%edx), %edi
addl $5, %edx
addl %edi, 44(%esp)
movzbl -4(%edx), %edi
addl %edi, %ebx
movzbl -3(%edx), %edi
addl %edi, %eax
movzbl -2(%edx), %edi
addl %edi, %ecx
movzbl -1(%edx), %edi
addl %edi, %esi
cmpl 40(%esp), %edx
jne L3
This keeps as many of the 'results' in registers for the duration of the calculation as it can (rather that constantly reading/writing them all to memory like your existing code). Fewer loops also means fewer cmp instructions, and this only makes one pass thru the buffer instead of 5. Compiling for x64 (much easier now that there's no asm) gives even better code, since there are more registers available.
Obviously this falls apart if MAXTOT gets bigger. But I can only comment on the code I can see, and 5 is what you used.
FWIW.