cipper cipper - 1 year ago 70
C Question

optimization of functions with many input parameters in C

I have a function which is inside a big loop in my code, and it occupies most of the cpu time:

inline void myfunc(double v1, ... , double vN){
(general, complex, multiline manipulation of v1 .. vN)
res = v1;

in which
is a global variable and the number N of passed arguments is about 20. I've tried to optimize the function calling by passing the variable pointers:

inline void myfunc(double *v1, ... , double *vN){
(general, complex, multiline manipulation of *v1 .. *vN)
res = *v1;

and then of course calling it by
myfunc(&v1, ..., &vN)
. I assume that in the first case at each call the function must create local v1..vN variables, while in the second case it doesn't need to.
I found that both versions work (duh!) but actually I get no speed up at all with the second case. Why is that?

Answer Source

Think about what you're doing:

  • In the first version of myfunc, you're passing N double parameters by value, making N copies of sizeof(double).

  • In the second version, you're passing N double* parameters by value, then accessing them. You're making N copies of sizeof(double*), then following a pointer indirection. Passing pointers/references also prevents the compiler from performing more aggressive optimizations.

In short, the second version is doing more work than the first one. If you see no difference, it's likely that the compiler was able to optimize the indirections/copies away.

You can use the awesome website to easily compare the generated assembly for both versions, on multiple compilers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download