为什么此动态数组实现比std :: vector <T>慢?

时间:2019-11-30 05:30:52

标签: c++ malloc

Bellow是使用malloc和realloc的简单模板数组实现

通过调试器逐步执行,代码步骤少于矢量。 但是,使用std :: chrono计时时,std :: vector仍然更快。

这是为什么?

(使用gnu cc v9进行编译)

#include <../array.hpp>
#include <../console.hpp>

#include <vector>

int main() {
    console::time("array");
    array<int> a { 1, 2, 3, 4, 5, 6, 7 };
    console::timeEnd("array");
    for (unsigned int i = 0; i < a.size(); i++) {
        console::log(std::to_string(a[i]));
    }

    array<int> b { 1, 2, 3, 4, 5, 6, 8 };
    if (a != b) {
        console::log("a != b");
    }

    array<int> c { 1, 2, 3, 4, 5, 6, 7 };
    if (a == c) {
        console::log("a == c");
    }

    console::time("std::vector");
    vector<int> v { 1, 2, 3, 4, 5, 6, 7 };
    console::timeEnd("std::vector");
    for (unsigned int i = 0; i < v.size(); i++) {
        console::log(std::to_string(v[i]));
    }

    return 0;
};
array: 27µs - timer ended
1
2
3
4
5
6
7
a != b
a == c
std::vector: 2655ns - timer ended
1
2
3
4
5
6
7

完整的实现[此处](https://gist.github.com/universefullofthings/ac933d64158217478a02df7bdcc8f319 ?.

0 个答案:

没有答案