3

由于移动分配 std::vector 是一个O(1)时间操作,而将 std::vector 复制到另一个是O(N)(其中 N 是 2 个向量的大小之和),我希望看到移动分配具有显着的性能比抄袭更有优势。nums2为了测试这一点,我编写了以下代码,它将大小为 1000 到nums100,000 次的 std::vector 移动分配/复制。

#include <iostream>
#include <vector>
#include <chrono>

using namespace std;

int main()
{
    auto start = clock();

    vector <int> nums;
    for(int i = 0; i < 100000; ++i) {

        vector <int> nums2(1000);
        for(int i = 0; i < 1000; ++i) {
            nums2[i] = rand();
        }

        nums = nums2; // or nums = move(nums2);

        cout << (nums[0] ? 1:0) << "\b \b"; // prevent compiler from optimizing out nums (I think)
    }

    cout << "Time: " << (clock() - start) / (CLOCKS_PER_SEC / 1000) << '\n';

    return 0;
}

我使用的编译器是 g++ 7.5.0。使用 运行时g++ -std=c++1z -O3,移动分配/复制版本都需要大约 1600 毫秒,这与移动分配具有任何显着性能优势的假设不符。然后我测试了使用std::swap(nums, nums2)(作为移动分配的替代方法),但这也花了大约相同的时间。

所以,我的问题是,为什么将 std::vector 移动分配给另一个似乎比复制分配具有性能优势?我对 C++ 移动赋值的理解是否存在根本性错误?

4

0 回答 0