Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct in C, are they efficient?

I'm reading some C code like that:

double function( int lena,double xa,double ya, double za, double *acoefs, ...,
                 int lenb,double xb,double yb, double zb, double *bcoefs, ...,
                 same for c,
                 same for d )

This function is called in the code more than 100.000 times so it's performance-critical.

I'm trying to extend this code but I want to know if it's efficient or not (and how much this influences the speed) to encapsulate all the parameters in a struct like this

struct PGTO { int len; double x,y,z ; double *acoefs }

and then access the parameters in the function.

like image 244
pygabriel Avatar asked Mar 12 '10 09:03

pygabriel


1 Answers

Visual c++ 2008 64 bit seems to pass the structure by having the caller allocate space for a copy of the structure on it's stack and copying the data items into it and then passing just the address of that copy into the function by value.

This simple example compiled as follows -

struct data {
   int a;
   int b;
   int c;
   char d;
   float f;
};




double f2(data d)
{
    return d.a+d.b+d.c+d.d+d.f;
}

Compiles to this -

movsx   eax, BYTE PTR [rcx+12]
add eax, DWORD PTR [rcx+8]
add eax, DWORD PTR [rcx+4]
add eax, DWORD PTR [rcx]
movd    xmm0, eax
cvtdq2ps xmm0, xmm0
addss   xmm0, DWORD PTR [rcx+16]
unpcklps xmm0, xmm0
cvtps2pd xmm0, xmm0
ret 0

So basically when you pass individual items the caller pushed them onto the stack and the function accesses them relative to the stack. When you pass a strcuture the caller copies the data items into a block of memory on the stack and then passed the address of that into the function, which accesses them relative to that.

The second way has a couple more assembly languge instructions but that it, so as far as I can tell from my tests there is no significant difference in efficiency between the two methods at all other than a few microseconds. In all my tests the compiler wanted to inline any calls anyway unless I forced it to call it via a pointer so it's possible that nothing is passed via the stack at all in your real program anyway.

In my opinion using a struct is clearer and there appear to be no significant differences in speed so go for that one :)

As always, if in doubt over performance you need to profile your exact setup

like image 106
jcoder Avatar answered Oct 24 '22 07:10

jcoder