Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Optimizations [closed]

I've been raised in a very OO manner when it comes to programming, which has unfortunately meant that highly optimized code is not my forte. I'm fairly good at C now and can usually do things in reasonably intelligent ways, but I still have trouble thinking of the most optimized way to handle situations.

One example would be:

int strlen(const char* str)
{
    char* s;
    for (s=str; *s; ++s);
    return s-str;
}

I would never have thought of that myself.

So, what are some good resources that expose you to optimized code like this? I'd like to find a place where I could read up on the theory behind it, what the compiler does in the background which makes it worthwhile, etc.

It would also be nice if some resources were noted for studying optimized data structures with application to real-life scenarios, but that's probably too much to ask.

like image 230
John Humphreys Avatar asked Jul 28 '11 18:07

John Humphreys


1 Answers

Don't try too hard with micro optimizations. With modern day compilers it is best to let optimizations like those get handled by the compiler. It is better to spend your time choosing the right algorithms, and design patterns for your applications. Find a decent profiler and learn how to use it. Don't waste your time trying to figure out how to optimize strlen.

As for references in how to do these micro optimizations I have mentioned it before, but will gladly do so again, Agner's guide is simply outstanding, and free :) Check out: http://www.agner.org/optimize/ there should be plenty of guides.

BTW: The most optimised version of strlen I've come across is made by Agner: http://www.agner.org/optimize/asmlib-instructions.pdf and is written in assembly. ;-)

like image 98
Tommy Andersen Avatar answered Sep 28 '22 09:09

Tommy Andersen