Home Optimizing a function for either a pointer or a scalar
Reply: 0

Optimizing a function for either a pointer or a scalar

user1119
1#
user1119 Published in April 25, 2018, 6:03 pm

I have a complicated program that I am trying to optimize. After some testing I isolated a function that looks as follows:

void sum(int* res, int* a, int* b, int size){
    for (int i=0;i<size;i++){
       res[i] = a[i] * (b[i]+1);
    }
}

I frequently call this function with a repeated second or third argument, so I optimized it as follows

void sum(int* res, int* a, int b, int size){
    for (int i=0;i<size;i++){
       res[i] = a[i] * (b+1);
    }
}

or as follows

void sum(int* res, int a, int* b, int size){
    for (int i=0;i<size;i++){
       res[i] = a * (b[i]+1);
    }
}

Note that the second or third argument are either scalars or pointers. Is there a way to use C++ template magic to have all three versions without having to repeat the implementation?

DISCLAIMER: My function, which is too complicated to list here, is not as simple as the example. But if I know how to write the template for this simple example, I should be able to adapt the solution to my problem.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.355162 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO