为什么排序不及时获取O(n log(n))

sch*_*312 7 c++ sorting time performance-testing

在以下代码段中,时间消耗为std::sort。这应该花费O(nlog(n))时间。std::chrono仅用于测量std::sort

我使用具有优化级别的Intel编译器18.0.3编译了以下代码-O3。我使用Redhat6。

#include <vector>
#include <random>
#include <limits>
#include <iostream>
#include <chrono>
#include <algorithm>

int main() {
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist(std::numeric_limits<int>::min(),
                                                                  std::numeric_limits<int>::max());

    int ret = 0;

    const unsigned int max = std::numeric_limits<unsigned int>::max();
    for (auto j = 1u; j < max; j *= 10) {
        std::vector<int> vec;

        vec.reserve(j);

        for (int i = 0; i < j; ++i) {
            vec.push_back(dist(rng));
        }

        auto t_start = std::chrono::system_clock::now();
        std::sort(vec.begin(), vec.end());
        const auto t_end = std::chrono::system_clock::now();
        const auto duration = std::chrono::duration_cast<std::chrono::duration<double>>(t_end - t_start).count();
        std::cout << "Time measurement: j= " << j << " took " << duration << " seconds.\n";
        ret + vec[0];
    }
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

该程序的输出是

Time measurement: j= 1 took 1.236e-06 seconds.
Time measurement: j= 10 took 5.583e-06 seconds.
Time measurement: j= 100 took 1.0145e-05 seconds.
Time measurement: j= 1000 took 0.000110649 seconds.
Time measurement: j= 10000 took 0.00142651 seconds.
Time measurement: j= 100000 took 0.00834339 seconds.
Time measurement: j= 1000000 took 0.098939 seconds.
Time measurement: j= 10000000 took 0.938253 seconds.
Time measurement: j= 100000000 took 10.2398 seconds.
Time measurement: j= 1000000000 took 114.214 seconds.
Time measurement: j= 1410065408 took 163.824 seconds.
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

这似乎非常接近线性行为。

为什么std::sort要求O(n)而不是O(nlog(n))

Bat*_*eba 12

您呈现的图表非常适合y = x log (x)。与相比xlog(x)效果不大。我认为您的结果将x log (x)具有良好的意义。

这里没有惊喜。

这是您欣赏O(n log n)并不比O(n)差很多的试金石。

  • 就像我在评论中写道:在n log n的大型图表中,它看起来像线性函数:https://www.wolframalpha.com/input/?i=x+log+x+from+2+to+100000 (4认同)