Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I always questioned myself this, especially since - quite a few years ago - I also did such a test comparing the timings of a standard member method call with a virtual one and was really angry about the results at that time, having empty virtual calls being 8 times slower than non-virtuals.</p> <p>Today I had to decide whether or not to use a virtual function for allocating more memory in my buffer class, in a very performance critical app, so I googled (and found you), and in the end, did the test again.</p> <pre><code>// g++ -std=c++0x -o perf perf.cpp -lrt #include &lt;typeinfo&gt; // typeid #include &lt;cstdio&gt; // printf #include &lt;cstdlib&gt; // atoll #include &lt;ctime&gt; // clock_gettime struct Virtual { virtual int call() { return 42; } }; struct Inline { inline int call() { return 42; } }; struct Normal { int call(); }; int Normal::call() { return 42; } template&lt;typename T&gt; void test(unsigned long long count) { std::printf("Timing function calls of '%s' %llu times ...\n", typeid(T).name(), count); timespec t0, t1; clock_gettime(CLOCK_REALTIME, &amp;t0); T test; while (count--) test.call(); clock_gettime(CLOCK_REALTIME, &amp;t1); t1.tv_sec -= t0.tv_sec; t1.tv_nsec = t1.tv_nsec &gt; t0.tv_nsec ? t1.tv_nsec - t0.tv_nsec : 1000000000lu - t0.tv_nsec; std::printf(" -- result: %d sec %ld nsec\n", t1.tv_sec, t1.tv_nsec); } template&lt;typename T, typename Ua, typename... Un&gt; void test(unsigned long long count) { test&lt;T&gt;(count); test&lt;Ua, Un...&gt;(count); } int main(int argc, const char* argv[]) { test&lt;Inline, Normal, Virtual&gt;(argc == 2 ? atoll(argv[1]) : 10000000000llu); return 0; } </code></pre> <p>And was really surprised that it - in fact - really does not matter at all anymore. While it makes just sense to have inlines faster than non-virtuals, and them being faster then virtuals, it often comes to the load of the computer overall, whether your cache has the necessary data or not, and whilst you might be able to optimize at cache-level, I think, that this should be done by the compiler developers more than by application devs.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload