C++ VS2019发布模式下的迭代器性能问题
我正在做选择排序(家庭作业)的基准测试,我想尝试一下。当比较好的旧代码(基于C++ VS2019发布模式下的迭代器性能问题,c++,performance,sorting,iterator,C++,Performance,Sorting,Iterator,我正在做选择排序(家庭作业)的基准测试,我想尝试一下。当比较好的旧代码(基于int而不是随处可见的iterator)时,在调试模式下,现代代码比旧代码快,但是在发布模式下,它比旧代码慢2倍。这真令人困惑。我是否应该继续使用旧代码,因为如果STL已经存在,为什么要重新发明轮子? 奇怪的是,是什么导致迭代器在调试时更快,而在发布时更差,难道不是相反吗 Debug: 100k min_element: 210s old: 288s Release: 100k min_eleme
int
而不是随处可见的iterator
)时,在调试模式下,现代代码比旧代码快,但是在发布模式下,它比旧代码慢2倍。这真令人困惑。我是否应该继续使用旧代码,因为如果STL已经存在,为什么要重新发明轮子?奇怪的是,是什么导致迭代器在调试时更快,而在发布时更差,难道不是相反吗
Debug:
100k
min_element: 210s
old: 288s
Release:
100k
min_element: 10s
old: 4s
我的测试代码:
void selection(std::vector<int>& arr)
{
for (auto it = arr.begin(); it != arr.end(); ++it) {
auto const selection = std::min_element(it, arr.end());
std::iter_swap(selection, it);
}
}
void selection_old(std::vector<int>& arr)
{
int i, j, min_idx;
for (i = 0; i < arr.size() - 1; i++)
{
min_idx = i;
for (j = i + 1; j < arr.size(); j++)
if (arr[j] < arr[min_idx])
min_idx = j;
std::swap(arr[min_idx], arr[i]);
}
}
void selection_it(std::vector<int>& arr)
{
auto min_idx = arr.begin();
for (auto i = arr.begin(); i != arr.end(); i++)
{
min_idx = i;
for (auto j = i; j != arr.end(); j++)
if (*j < *min_idx)
min_idx = j;
std::iter_swap(min_idx, i);
}
}
auto benchmark(std::vector<int> input, std::function<void(std::vector<int>&)> sort)
{
using namespace std::chrono;
auto start = high_resolution_clock::now();
sort(input);
auto stop = high_resolution_clock::now();
auto result = duration_cast<milliseconds>(stop - start).count();
return result;
}
int main()
{
std::vector<int> set(100000);
std::iota(set.begin(), set.end(), 0);
std::reverse(set.begin(), set.end());
std::cout << benchmark(set, selection) << std::endl;
std::cout << benchmark(set, selection_it) << std::endl;
std::cout << benchmark(set, selection_old) << std::endl;
}
在每次循环迭代中,基于迭代器的方法不断地反复计算
arr.end()
。我希望这会被优化掉,但也许优化器出于某种原因变得愚蠢了。
g++
300k
min_element: 33s
old: 26s
it: 34s