gpt4 book ai didi

c++ - 超速 vector push_back

转载 作者:太空宇宙 更新时间:2023-11-04 16:01:00 24 4
gpt4 key购买 nike

<分区>

当无法预测容量时,我正在尝试加速 vector::push_back

当 reserve 可用时, vector push_back 将新元素写入容器的末尾,然后移动结束标记。 reserve全部用完后,push_back可能会触发reallocation,这是一个缓慢的过程。
为了加快速度,为几个即将到来的 push_back 重新生成 reserve,而不会在空时重新分配。您认为此代码如何帮助实现该目标?

#ifndef __VECTOR_HPP
#define __VECTOR_HPP
#include <exception>
#include "Concept.hpp" //Concept::RESA constant
#include <vector>
template <typename T>
class Vector : public std::vector<T> {
public :
void push_back (T t) {
if (std::vector<T>::size () == std::vector<T>::capacity ()) {
std::vector<T>::reserve ((size_t) Concept::RESA);
}
std::vector<T>::push_back (t);
}
};
#endif

测试程序:

#include "Vector.hpp"

int main (int argc, char* argv []) {
{
std::vector<size_t> v0;
clock_t t (clock ());
size_t duration (0);
for (size_t i (0); i != 10000000; i++) {
v0.push_back (i);
}
duration = (size_t) (clock () -t);
std::cout << "duration old push_back == " << duration << " ticks" << std::endl;
}
{
size_t duration (0);
Vector<size_t> v1;
clock_t t (clock ());
for (size_t i (0); i != 10000000; i++) {
v1.push_back (i);
}
duration = (size_t) (clock () -t );
std::cout << "duration new push_back == " << duration << " ticks" << std::endl;
}
}

结果:

使用 Concept::RESA == 8192,并应用建议,这里是 Lenovo ThinkCentre icore5(Linux Debian,g++)上的结果:

duration old push_back == 105317 ticks

duration new push_back == 87156 ticks

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com