samedi 25 septembre 2021

Why doesn't move-assigning a std::vector seem to have any performance benefit over copying in this code?

Since move-assigning a std::vector is is a O(1) time operation and copying a std::vector to another is O(N) (where N is the sum of the sizes of the 2 vectors), I expected to see move-assignment having a significant performance advantage over copying. To test this, I wrote the following code, which move-assigns/copies a std::vector nums2 of size 1000 to nums 100,000 times.

#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;
}

The compiler I am using is g++ 7.5.0. When running with g++ -std=c++1z -O3, both the move-assign/copy versions take around 1600ms, which does not match with the hypothesis that move-assignment has any significant performance benefit. I then tested using std::swap(nums, nums2) (as an alternative to move-assignment), but that also took around the same time.

So, my question is, why doesn't move-assigning a std::vector to another seem to have a performance advantage over copy-assignment? Do I have a fundamental mistake in my understanding of C++ move-assignment?

Aucun commentaire:

Enregistrer un commentaire