Optimization with C++ Template

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.


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.


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.


About Moto

Engineer who likes coding
This entry was posted in Optimization. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s