Note that there are some explanatory texts on larger screens.

plurals
  1. POPerformance of qsort vs std::sort?
    text
    copied!<p>According Scott Meyers, in his Effective STL book - item 46. He claimed that <a href="http://en.cppreference.com/w/cpp/algorithm/sort" rel="noreferrer"><code>std::sort</code></a> is about 670% faster than <a href="http://en.cppreference.com/w/cpp/algorithm/qsort" rel="noreferrer"><code>std::qsort</code></a> due to the fact of inline. I tested myself, and I saw that qsort is faster :( ! Could anyone help me to explain this strange behavior? </p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;cstdio&gt; const size_t LARGE_SIZE = 100000; struct rnd { int operator()() { return rand() % LARGE_SIZE; } }; int comp( const void* a, const void* b ) { return ( *( int* )a - *( int* )b ); } int main() { int ary[LARGE_SIZE]; int ary_copy[LARGE_SIZE]; // generate random data std::generate( ary, ary + LARGE_SIZE, rnd() ); std::copy( ary, ary + LARGE_SIZE, ary_copy ); // get time std::time_t start = std::clock(); // perform quick sort C using function pointer std::qsort( ary, LARGE_SIZE, sizeof( int ), comp ); std::cout &lt;&lt; "C quick-sort time elapsed: " &lt;&lt; static_cast&lt;double&gt;( clock() - start ) / CLOCKS_PER_SEC &lt;&lt; "\n"; // get time again start = std::clock(); // perform quick sort C++ using function object std::sort( ary_copy, ary_copy + LARGE_SIZE ); std::cout &lt;&lt; "C++ quick-sort time elapsed: " &lt;&lt; static_cast&lt;double&gt;( clock() - start ) / CLOCKS_PER_SEC &lt;&lt; "\n"; } </code></pre> <p>This is my result:</p> <pre><code>C quick-sort time elapsed: 0.061 C++ quick-sort time elapsed: 0.086 Press any key to continue . . . </code></pre> <p><strong>Update</strong></p> <p>Effective STL 3rd Edition ( 2001 )<br> Chapter 7 Programming with STL<br> Item 46: Consider function objects instead of functions as algorithm parameters. </p> <p>Best regards, </p>
 

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