I wanted to show my team why move semantics can save resources. So I wrote some code to get some numbers for the talk. However, during this work I found something interesting which I did not fully understand. Copying a vector of pairs took substantially longer than copying a vector of an equivalent struct. Any ideas why?
Output:
std::pair<int,int>
===============
- sizeof type: 8
- sizeof container: 16
- copy = 80392 microseconds
- move = 6 microseconds
PAIR
====
- sizeof type: 8
- sizeof container: 16
- copy = 6377 microseconds
- move = 8 microseconds
Code:
#include <iostream>
#include <vector>
#include <chrono>
template <typename T>
void
MoveCopyComp()
{
std::vector<T> list;
T dummy;
std::cout << "- sizeof type: " << sizeof(T) << "\n";
std::cout << "- sizeof container: " << sizeof(list) << "\n";
for (int num = 0; num < 1000000; ++num)
list.push_back(dummy);
auto t0 = std::chrono::steady_clock::now();
std::vector<T> copy = list;
auto t1 = std::chrono::steady_clock::now();
std::vector<T> movement = std::move(list);
auto t2 = std::chrono::steady_clock::now();
std::cout << "- copy = "
<< std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count()
<< " microseconds\n";
std::cout << "- move = "
<< std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count()
<< " microseconds\n";
}
struct PAIR
{
int a;
int b;
};
int main(int argc, char **argv)
{
std::cout << "std::pair<int,int>\n===============\n";
MoveCopyComp<std::pair<int,int>>();
std::cout << "\nPAIR\n====\n";
MoveCopyComp<PAIR>();
}