I have a large array (image) and I need to do many small configurable computations on that data. I'll post an example here. NOTE: This is not the actual problem, but a minimal / hopefully illustrative example of what I need to do.
// different functions that can be called based on the configuration
float func1( float* a )
{
return (*a) * (*a);
}
float func2( float* a )
{
return (*a) + (*a);
}
float func3( float* a )
{
return 2 * (*a) * (*a);
}
// my data
float* data = new float[1024*1024];
// function that manages the configurations
int main( )
{
int param1 = 0;
int param2 = 1;
for ( int k = 0; k < 1024*1024; k++ )
{
if ( param1 == 2 && param2 == 0 )
data[k] = func1( data + k );
else if ( param1 == 1 && param2 == 1 )
data[k] = func2( data + k );
else if ( param1 == 0 && param2 == 1 )
data[k] = func3( data + k );
else
continue;
}
}
In my code, it does not make sense to put the loop inside of each function.
However, param1 and param2 remain constant during the loop and they are known at compile time.
Is there a way to remove the influence of the if/elseif statements?
constexpr
(orconst
) and the compiler should be able to optimize away the checks and only call the one function. Look at the generated assembly code if you're unsure. Also, if a function is not called, then there's no overhead. And if the functions you call are small, mark them asinline
for possibly more optimization alternatives. And mark the arguments asconst
if you do not modify them. And why pass the arguments as pointers? The indirection will add overhead.-S
.