Search code examples
c++performanceexecution-time

Not using functions for speed? (C++)


I'm writing a program for a competition in my class. It already works great and now I'm trying to make it as fast as possible. My question is- would just pasting what a function returns, wherever I want to use it, speedup my program as compared to making a user defined function? I know that function calls causes a jump in memory, so does doing this measurably speedup my code? I don't care about readability in this case

Eg. Instead of doing this

while(something){
y = function();
}
double function(){
return f(x);
}

I do this

while(something){
y = f(x);
}

I've already done stuff like passing structures by reference, avoiding casting, using shift operations, using things like ++i, etc. for a faster execution time, and I'm looking to gain a small edge.


Solution

  • In general, none of that ought to matter.

    Optimizing compilers are really, really good at determining when to perform strength reduction (turning multiplication into adds or shifts) or inlining (eliminating the overhead of the function call).

    You should focus your time and effort, as a human, on writing concise, maintainable and readable code, with the right algorithmic complexity, and then rely on the compiler to do the right optimizations.

    You may find in rare circumstances that manual inlining (what you're doing) will yield significant perf benefits, but you should let a profiler guide you to the places where doing that will be beneficial. Not just doing it because you think it'll be faster, because it usually won't.

    Also, you noted in a comment reply that you're not compiling with -O3. That means you're getting no optimization help from the compiler. Add -O3.