c++ - qsort 与 std::sort 的性能?

标签 c++ performance sorting stl

根据 Scott Meyers 在他的 Effective STL 书 - item 46 中的说法。他声称 std::sortstd::qsort 快大约 670%由于内联的事实。我测试了自己,发现 qsort 更快 :( !谁能帮我解释一下这种奇怪的行为?

#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 << "\n";
    // 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 << "\n";
}

这是我的结果:

C quick-sort time elapsed: 0.061
C++ quick-sort time elapsed: 0.086
Press any key to continue . . .

更新

有效的 STL 第 3 版(2001 年)
第 7 章 STL 编程
第 46 条:考虑函数对象而不是函数作为算法参数。

最佳答案

std::clock() 不是可行的计时时钟。您应该使用特定于平台的更高分辨率计时器,例如 Windows 高性能计时器。不仅如此,你调用clock()的方式是,首先将文本输出到控制台,包含在时间中。这肯定会使测试无效。此外,请确保您在编译时使用了所有优化。

最后,我复制并粘贴了您的代码,qsort 得到 0.016,std::sort 得到 0.008。

关于c++ - qsort 与 std::sort 的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4708105/

相关文章:

c++ - TeamCity 中的 Visual Studio 企业代码覆盖率报告

javascript - 许多图像加载 HTML/Javascript 性能

Python 排序字典 : Key [Ascending] and then Value [Descending]

php - 打印垂直排序的 4 列数组

python - django order_by 查询集,升序和降序

c++ - C++ 中的 Qt3d 输入

c++ - 删除用户定义的 C++ 头文件中的 .h 扩展名

c++ - 在 C++ 中声明泛型 istream

python - 为 20,000 多个更新优化 Sqlite3

mysql - 获取多个表数据而不损失性能?