Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
Consider the following program. Why is move slower than copy? I thought that move semantics sped things up considerably when returning locals as rvalues from functions. Can you tell me why moving a large vector is slower than copying it. The benchmark for returning a shared_ptr is provided as a base case.
#include <iostream>
#include <vector>
#include <string>
#include <chrono>
using namespace std;
vector<int> getStringByCopy()
{
vector<int> v;
for (int x = 0; x< 15000000;x++) v.push_back(x);
return v;
}
vector<int>&& getStringByMove()
{
vector<int> v;
for (int x = 0; x< 15000000;x++) v.push_back(x);
return move(v);
}
shared_ptr<vector<int>> getStringByPointer()
{
shared_ptr<vector<int>> v = make_shared<vector<int>>();
for (int x = 0; x< 15000000;x++) v->push_back(x);
return v;
}
int main(int argc, const char * argv[]) {
// insert code here...
chrono::system_clock::time_point begin = chrono::system_clock::now();
vector<int> v = getStringByCopy();
chrono::system_clock::time_point end = chrono::system_clock::now();
cout << v[0] << "copy took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;;
begin = chrono::system_clock::now();
vector<int>&& m = getStringByMove();
end = chrono::system_clock::now();
cout << m[0] << "move took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;;
begin = chrono::system_clock::now();
shared_ptr<vector<int>> sp = getStringByPointer();
end = chrono::system_clock::now();
cout << (*sp)[0] << "pointer took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;
return 0;
}
The output is:
0copy took 437043
0move took 462803
0pointer took 394549
Your method that is supposed to return per copy already return per move. If you return anything that were allocated on the stack per value in a method and return it, then you get a automatic move.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
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>();
}
Oh face palm! Mike Vine hit it right on the shnoz.
I was using my debug build settings and not optimised.
Here are my optimised results for the same code:
std::pair<int,int>
===============
- sizeof type: 8
- sizeof container: 12
- copy = 2388 microseconds
- move = 0 microseconds
PAIR
====
- sizeof type: 8
- sizeof container: 12
- copy = 2672 microseconds
- move = 0 microseconds
Thanks everyone for the comments :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Im trying to save a char that im going to pop out of the char vector can you do that? If so how?
You are saving the character. This code
char char_toInt = vect[vect.size() - 1];
saves the character perfectly well. Not sure why you thought that was incorrect.
The mistake is the next line
int new_int = stoi(char_toInt);
Instead do it like this
int new_int = char_toInt - '0';
stoi is for a string and you have a char. These are not the same thing, and C++ is fussy about types.
Instead to convert a digit char to it's integer value just subtract '0' from the char. All chars are represented as integers internally (lookup ASCII if you are interested in the how this might be done). Subtracting '0' gives you the difference between the integer corresponding to your digit and the integer corresponding to '0'. Since the integers corresponding to the digits are guaranteed to be sequential this gives you the value of your digit.
Well, you can write something like this
#include <vector>
#include <iostream>
int main()
{
std::vector<char> v;
v.push_back('a');
v.push_back('b');
v.push_back('c');
std::cout << v.back() << std::endl;
v.pop_back();
std::cout << v.back() << std::endl;
v.pop_back();
std::cout << v.back() << std::endl;
v.pop_back();
return 0;
}
which would produce an output of
c
b
a
Alternatively, you can also use a queue:
#include <queue>
#include <iostream>
int main()
{
std::queue<char> q;
q.push('a');
q.push('b');
q.push('c');
std::cout << q.front() << std::endl;
q.pop();
std::cout << q.front() << std::endl;
q.pop();
std::cout << q.front() << std::endl;
q.pop();
return 0;
}
which would produce an output of:
a
b
c
Or, alternatively, you can use a stack:
#include <stack>
#include <iostream>
int main()
{
std::stack<char> s;
s.push('a');
s.push('b');
s.push('c');
std::cout << s.top() << std::endl;
s.pop();
std::cout << s.top() << std::endl;
s.pop();
std::cout << s.top() << std::endl;
s.pop();
return 0;
}
which would produce an output of:
c
b
a
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a vector of string including :- chemistry physics maths.
I want to access first character of each word ie c of chemistry p of physics and m of maths. How to do that?
You can output the first index element through this process.
I have made a 2D vector and applied a for loop so each row of the vector's first element is printed.
#include <iostream>
#include <vector>
int main()
{
std::vector<std::string> vec = {"chemistry", "maths", "physics"};
for(int i=0;i<vec.size();i++)
{
std::cout << vec[i][0];
}
return EXIT_SUCCESS;
}
You can also use a range based for loop
for (auto &i : vec)
std::cout << i[0] << " ";
The output will be
c m p
You can treat it like a 2D matrix of characters.
Given the vector of strings:
std::vector<std::string> vec = {"chemestry", "physics", "math"};
You can use a normal loop to access all first characters:
for (int i = 0; i < vec.size(); i++)
std::cout << vec[i][0] << " ";
Or a range based loop:
for (auto &str : vec)
std::cout << str[0] << " ";
Output:
c p m
I think this code should do the trick. If not then the Compiler is being a racist and doesn't like you that much. In that case you can just go-to your old buddy cpp.sh :D
String is a char Array and you can access it's contents from indexes like so
std::string str = "Hello";
std::cout << "First Index: " << str[0];
Output:-
H
Same goes for the vector as well
std::vector <char> str = "World!";
std::cout << "First Index: " << str[0];
Output:-
W
Now if you combine those two, it makes it a 2D Array so you have to access it like you access data from a 2D Array/Matrix.
std::vector <std::string> str = {"Hello", "World", "!"};
std::cout << "First Index Of Element 1: " << str[0][0] << std::endl
<< "First Index Of Element 2: " << str[1][0] << std::endl
<< "First Index Of Element 3: " << str[2][0] << std::endl;
Output:-
H
W
!
Program:-
#include <iostream>
#include <vector>
int main() {
std::vector <std::string> vec = {"chemistry", "physics", "math"};
for (int i=0; i < vec.size(); i++) { //-- size(); Function gives the size of a vector
std::cout << vec[i][0] << std::endl;
}
return 0;
}
Output:-
c
p
m
Press any key to continue...
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
void printTop5()
{
int counter = 1;
int x, y;
float civ;
cout << "Total no. of records available = " << pointVector.size();
cout << "Printing top 5 exploration destinations....";
sort(pointVector.begin(), pointVector.end(), ascendingCiv);
for (int i = 0; i < 5; i++)
{
PointTwoD p1 = pointVector[i];
x = p1.getX();
y = p1.getY();
civ = p1.getCivIndex();
cout << counter << ")\t";
if (civ > 0)
{
cout << "Civ idx: " << civ << " ; at sector(" << x << "," << y < ")\n";
}
else
cout << "<No records available>";
}
}
bool ascendingCiv(const PointTwoD &d1, const PointTwoD &d2)
{
return d1.getCivIndex() > d2.getCivIndex();
}
When I run this function I get this fault whereby it says segmentation fault core dumped. Any idea? Heard its about some memory problem.
One issue is that you are not checking whether you actually have at least 5 elements in your vector:
for (int i = 0; i < 5; i++)
{
PointTwoD p1 = pointVector[i];
If i is out-of-bounds of the vector, accessing pointVector[i] would invoke undefined behavior.
The loop condition can be changed to the following:
#include <algorithm>
//...
size_t loopEnd = std::min(pointVector.size(), 5);
for (size_t i = 0; i < loopEnd; i++)
{
PointTwoD p1 = pointVector[i];
The loop will either go up to the size of the vector or 5 elements, whichever is smaller.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Let's assume C++ for loop in the form of:
for(int i; i<10;i++)
So the integer needs to be allocated in the beginning and then increased at every step the as well as compared. So wouldn't it be faster to do something like that:
f or(int i; i++<10;)
since the variable doesn't need to be loaded into the storage again? espacially when making it volatile?
This little example code gave the same result for all the cases. Does the for loop get optimized anyway or am I missing something?
#include<iostream>
#include<ctime>
int main() {
time_t start,ende;
volatile int dummy = 1;
const int rep = 1000000000;
// Method 1
start = time(0);
for (int i = 0; i < rep; i++)
dummy = 1;
ende = time(0);
std::cout << "Method 1: " << difftime(ende,start)*1000 << " ms" << std::endl;
// Method 2
start = time(0);
for (int i = 0; i++ < rep; )
dummy = 1;
ende = time(0);
std::cout << "Method 2: " << difftime(ende,start)*1000 << " ms" << std::endl;
// Method 3
start = time(0);
for (volatile int i = 0; i < rep; i++)
dummy = 1;
ende = time(0);
std::cout << "Method 3: " << difftime(ende,start)*1000 << " ms" << std::endl;
}
OS: Linux
Compiler: g++
Optimization: standart (no flag)
Compilers are a lot smarter than you think. They won't produce the kind of spurious load that you think they do.
Optimization depends on compiler and its options.
I'd suggest you to disassemble your code and see what's the result of the optimization.
A simple good disassemble e.g. HT editor or IDA version 5 (it free now). For small piece of code it will be easy enough.