問題描述
根據 Scott Meyers 的說法,在他的 Effective STL 書中 - 第 46 項.他聲稱std::sort
比 std::qsort
由于內聯的事實.我測試了自己,發現 qsort 更快 :( !誰能幫我解釋一下這種奇怪的行為?
According to Scott Meyers, in his Effective STL book - item 46. He claimed that std::sort
is about 670% faster than std::qsort
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?
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <cstdio>
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 << "C quick-sort time elapsed: " << static_cast<double>( clock() - start ) / CLOCKS_PER_SEC << "
";
// get time again
start = std::clock();
// perform quick sort C++ using function object
std::sort( ary_copy, ary_copy + LARGE_SIZE );
std::cout << "C++ quick-sort time elapsed: " << static_cast<double>( clock() - start ) / CLOCKS_PER_SEC << "
";
}
這是我的結果:
C quick-sort time elapsed: 0.061
C++ quick-sort time elapsed: 0.086
Press any key to continue . . .
更新
Effective STL 第三版(2001 年)
第 7 章 STL 編程
第 46 條:將函數對象而不是函數視為算法參數.
Effective STL 3rd Edition ( 2001 )
Chapter 7 Programming with STL
Item 46: Consider function objects instead of functions as algorithm parameters.
推薦答案
std::clock() 不是可行的計時時鐘.您應該使用特定于平臺的更高分辨率計時器,例如 Windows 高性能計時器.更重要的是,您調用 clock() 的方式是首先將文本輸出到控制臺,該控制臺包含在時間中.這肯定會使測試無效.此外,請確保您使用所有優化進行編譯.
std::clock() is not a viable timing clock. You should use a platform-specific higher resolution timer, like the Windows High Performance Timer. More than that, the way that you call clock() is that first, text is output to the console, which is included in the time. This definitely invalidates the test. In addition, make sure that you compiled with all optimizations.
最后,我復制并粘貼了您的代碼,qsort 為 0.016,std::sort 為 0.008.
Finally, I copied and pasted your code, and got 0.016 for qsort and 0.008 for std::sort.
這篇關于qsort 與 std::sort 的性能?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!