Why does std::nth_element()
run so much faster, when it is given pointers instead of iterators? 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.
Using iterators, the following code (not including allocation of the vector) ran in 1200 milliseconds:
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:
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. The examples were compiled with Embarcadero C++ Builder XE8 version 22.0.19027.8951, Release build and "Generate fastest possible code" setting. These tests were ran during different executions so they should not affect each other.
我的猜测是编译器要么没有做好优化,要么你正在调试模式下构建,编译器使用特殊的,调试(慢)版本的STL容器。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.