Saturday, June 25, 2016

std::move example

Here is an example of move semantics:

#include <string>
#include <vector>
#include <utility>
#include <iostream>
const int STR_SIZE = 10000000;
const int VEC_SIZE = 200000000;
int main()
{
std::vector<std::string> vec;
std::string str;
for (int i = 0; i < STR_SIZE; ++i)
{
str += 'a';
}
for (int i = 0; i < VEC_SIZE; ++i)
{
vec.push_back(str);
}
std::vector<std::string> vec1(vec);
//std::vector<std::string> vec1(std::move(vec));
std::cout << vec1.size() << std::endl;
std::cout << vec.size() << std::endl;
return 0;
}
view raw c.cpp hosted with ❤ by GitHub
When line 24 is used:

nonbonding@castor-ub:~/dnonbonding/tmp/rvalue$ g++ -std=c++11 c.cpp && time ./a.out
200000000
200000000

real 0m31.475s
user 0m24.932s
sys 0m4.604s

When line 25 is used instead of line 24:

nonbonding@castor-ub:~/dnonbonding/tmp/rvalue$ g++ -std=c++11 c.cpp && time ./a.out 
200000000
0

real 0m17.334s
user 0m16.708s
sys 0m0.440s

Execution time was reduced by almost a half!

No comments:

Post a Comment