简体   繁体   English

为什么STL算法的指针要比std :: vector迭代器快得多?

[英]Why are STL algorithms much faster with pointers than std::vector iterators?

Why does std::nth_element() run so much faster, when it is given pointers instead of iterators? 为什么std::nth_element()在给定指针而不是迭代器时运行得更快? I would expect std::vector and STL algorithms to be quite optimized, but my measurements show execution time drops by 75% when I change iterators to pointers. 我希望std::vector和STL算法得到很好的优化,但是当我将迭代器更改为指针时,我的测量显示执行时间下降了75%。

Using iterators, the following code (not including allocation of the vector) ran in 1200 milliseconds: 使用迭代器,以下代码(不包括向量的分配)在1200毫秒内运行:

std::vector<uint16_t> data(/* 50 million values */);

const double alfa = 0.01;
const double beta = 0.95;

std::nth_element(data.begin(), data.begin() + int(data.size() * alfa), data.end());
const uint16_t x = *(data.begin() + int(data.size() * alfa));

std::nth_element(data.begin(), data.begin() + int(data.size() * beta), data.end());
const uint16_t y = *(data.begin() + int(data.size() * beta));

Using pointers, the following code (not including allocation of the vector) ran in 350 milliseconds: 使用指针,以下代码(不包括向量的分配)在350毫秒内运行:

std::vector<uint16_t> data(/* 50 million values */);

const double alfa = 0.01;
const double beta = 0.95;

std::nth_element(&data.front(), &data.front() + int(data.size() * alfa),
    &data.front() + data.size());
const uint16_t x = *(data.begin() + int(data.size() * alfa));

std::nth_element(&data.front(), &data.front() + int(data.size() * beta),
    &data.front() + data.size());
const uint16_t y = *(data.begin() + int(data.size() * beta));

I observed similar speed increase with std::sort() as well. 我也观察到了与std::sort()相似的速度提升。 The examples were compiled with Embarcadero C++ Builder XE8 version 22.0.19027.8951, Release build and "Generate fastest possible code" setting. 这些示例使用Embarcadero C ++ Builder XE8版本22.0.19027.8951,发布版本和“生成最快可能代码”设置进行编译。 These tests were ran during different executions so they should not affect each other. 这些测试是在不同的执行期间运行的,因此它们不应相互影响。

我的猜测是编译器要么没有做好优化,要么你正在调试模式下构建,编译器使用特殊的,调试(慢)版本的STL容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM