Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speeding up virtual function calls in gcc

Profiling my C++ code with gprof, I discovered that a significant portion of my time is spent calling one virtual method over and over. The method itself is short and could probably be inlined if it wasn't virtual.

What are some ways I could speed this up short of rewriting it all to not be virtual?

like image 974
Wayne Kao Avatar asked Apr 01 '09 00:04

Wayne Kao


2 Answers

Are you sure the time is all call-related? Could it be the function itself where the cost is? If this is the case simply inlining things might make the function vanish from your profiler but you won't see much speed-up.

Assuming it really is the overhead of making so many virtual calls there's a limit to what you can do without making things non-virtual.

If the call has early-outs for things like time/flags then I'll often use a two-level approach. The checking is inlined with a non-virtual call, with the class-specific behavior only called if necessary.

E.g.

class Foo
{
public:

inline void update( void )
{
  if (can_early_out)
    return;

  updateImpl();
}

protected:

virtual void updateImpl( void ) = 0;    
}; 
like image 81
Andrew Grant Avatar answered Sep 30 '22 04:09

Andrew Grant


If the virtual calling really is the bottleneck give CRTP a try.

like image 34
DaClown Avatar answered Sep 30 '22 05:09

DaClown