Andreas Andreas - 2 months ago 17
C Question

how would you optimize this function?

#include <stdlib.h>
#include <cstring.h>
#include <time.h>

int cp[1000000][3];
int p[1000000][3];//assume this array to be populated

void main(){

srand(time(NULL));

for(n; n < 1000000; n++){
if (rand()%2)
memcpy(cp[n], p[n], 12);
}
}

}


This is a somewhat simplified version of the actual code I am using. This code takes up a significant part of my process I was wondering if I can optimize this with some clever tricks. I have used pointers before to avoid branching, but I can't figure out how to apply that here.

Answer

Getting rid of the floating point is one obvious improvement you should do. That part looks fishy, I assume you want a 50% probability that the code will copy the data?

The branch itself could be removed with some silly trick like:

int do_copy = rand() % 2;
memcpy(cp[n], p[n], 12*do_copy);

However, I wouldn't write such code without looking at the disassembly of the optimized code first.