我寫了一個小的測試比較舉動和測試語義:移動語義慢然後複製C++
#include <vector>
#include <iostream>
#include <iterator>
#include <chrono>
#include <iomanip>
using namespace std;
int main()
{
int lenLeft = 3;
int lenMid = 3;
vector<int> lenVec{10,100,1000,static_cast<int>(1e4),static_cast<int>(1e5),static_cast<int>(1e6),static_cast<int>(1e7)};
int reps = 100;
vector<double>delta_t_move;
vector<double>delta_t_copy;
//move
cout<<"move"<<endl;
{
for(int len : lenVec)
{
auto startTime = std::chrono::high_resolution_clock::now();
for(int i = 0; i<reps;i++)
{
vector<int> leftVec(len,0);
vector<int> rightVec;
move(leftVec.begin()+lenLeft+lenMid,leftVec.end(),std::back_inserter(rightVec));
leftVec.erase(leftVec.begin()+lenLeft+lenMid,leftVec.end());
vector<int> midVec;
std::move(leftVec.begin()+lenLeft,leftVec.begin()+lenLeft+lenMid,std::back_inserter(midVec));
leftVec.erase(leftVec.begin()+lenLeft,leftVec.begin()+lenLeft+lenMid);
}
auto endTime = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = endTime - startTime;
delta_t_move.push_back(elapsed.count());
}
}
//copy
cout<<"copy"<<endl;
{
for(int len : lenVec)
{
auto startTime = std::chrono::high_resolution_clock::now();
for(int i = 0; i<reps;i++)
{
vector<int> leftVec(len,0);
vector<int> rightVec = vector<int>(leftVec.begin()+lenLeft+lenMid,leftVec.end());
leftVec.erase(leftVec.begin()+lenLeft+lenMid,leftVec.end());
vector<int> midVec = vector<int>(leftVec.begin()+lenLeft,leftVec.begin()+lenLeft+lenMid);
leftVec.erase(leftVec.begin()+lenLeft,leftVec.begin()+lenLeft+lenMid);
}
auto endTime = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = endTime - startTime;
delta_t_copy.push_back(elapsed.count());
}
}
for(int i = 0; i<lenVec.size();i++)
{
cout<<"lenVec = "<<setw(40)<<lenVec.at(i)<<"\t\t : delta_t_copy/delta_t_move = "<< delta_t_copy.at(i)/delta_t_move.at(i)<<endl;
}
return 0;
}
我得到這個程序的輸出是:
move
copy
lenVec = 10 : delta_t_copy/delta_t_move = 0.431172
lenVec = 100 : delta_t_copy/delta_t_move = 0.257102
lenVec = 1000 : delta_t_copy/delta_t_move = 0.166006
lenVec = 10000 : delta_t_copy/delta_t_move = 0.108573
lenVec = 100000 : delta_t_copy/delta_t_move = 0.113769
lenVec = 1000000 : delta_t_copy/delta_t_move = 0.134912
lenVec = 10000000 : delta_t_copy/delta_t_move = 0.133874
我劈開初始向量尺寸爲len
,分成3件。第一塊長度爲3,中間長度爲3,其餘尺寸爲len-6
。 我的結果顯示覆制語義要比移動語義快得多。
我正在使用MSVC2015。
任何想法如何可以是真實的?移動語義在什麼情況下更快?
發佈[MCVE],而不是指向博客文章的鏈接。 –
哦,我喜歡通過代碼橫向滾動...... – DeiDei
除此之外,你正在「移動」int。這是沒有意義的。 – DeiDei