Quantcast
Channel: CODE: Sequoia » Optimization
Viewing all articles
Browse latest Browse all 5

Optimization with C++ Template

$
0
0

C++ template can be used for enabling optimization. For example, you have a function:

void foo(int x){
// ... int v = n / x; // slow division operation // ... }

And call it.

foo(16);

Let’s assume foo is not inlined. A typical compiler is not allowed to optimize the division operator because it doesn’t know what’s the value of ‘x’ until the runtime.

 

Now, you rewrite the function to:

template<int x>
void foo(){
// ... int v = n / x;
// ... }

And call it.

foo<16>();

The division operator is optimized to shift operator because the compiler knows x is 16.

While it sounds too simple, you would be surprised that this technique can be applied very often. A number of functions are designed to take parameters just for re-usability purpose and their parameters are actually constant in a program.

For example, I have a function which takes width and height of an image and performs DCT on it. While the parameters can be any value, they are typically fixed to 16×16 or 8×8 (=block size). Another example is an audio filter function which takes coefficient vector and the size. The vector size is probably just 1024 and no other values.



Viewing all articles
Browse latest Browse all 5

Trending Articles