Performance Lack in my C++ Code [closed] - c++

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
At the moment i'm trying to optimize my c++ code to get better performance, because I have a strong java/c# background.
I've tested simple examples like getter/setter between classes and realized using them with references like this:
vector<string>& MyClass::getNum()
{
return num;
}
void MyClass::setNum(vector<string> &num)
{
this->num = num;
}
(let say 15+ Strings are in the Vector)
is faster 2x faster than without. (no difference when using simple/small parameter, but huge diff. when using Vectors etc.)
I also tried the same example in Java, but somehow my Java code is still faster than in C++.
Someone can help me?

In java, everything is pointer, so when you do this in java:
void function (ArrayList <Integer> myList);
It's almost equivalent in C++ to:
void function (std::vector <int> & myList);
void function (std::vector <int> * myList);
This answer your question on why Java is faster when not using reference in C++, because references are faster in most cases. Then, why does it improve performance?
Well, imagine you have a vector of int, if you pass it to a function without reference, you have to make a copy of the object (call the copy constructor), which take (in general) a huge amount of time since you have to allocate a new array, etc. Another example with a struct:
struct X {
int a[100] ;
int b[100] ;
} ;
This struct take something like 2 * 100 * 4 = 800 bytes on a modern machine (may vary of course), so if you pass it to a function like that:
void function (X x) ;
When you call the function, you need to make a copy, so a copy of 800 bytes, if you do:
void function (X const& x) ;
You only pass a reference to the object, i.e. something pointing to the object, which will take (on a x64 architecture), 8 bytes.

this->num = num; : this line copies the vector you passed by reference. If your goal is to give the vector to MyClass and then forget about it, consider passing it by rvalue reference and moving it.

Related

What is the better form to write Loop functions end with pointers in c++? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I know two forms to write loop functions with pointers in c++: using size of array or using the end of array.
Use the length:
float summationArray(float* numbers, int length){
if(length == 1){
return *numbers;
}
return *numbers + summationArray(numbers + 1, length - 1);
}
Use the end
float summationArray(float* numbers, float* end){
if(numbers == end){
return *numbers;
}
return *numbers + summationArray(numbers + 1, end);
}
What's is the better option?
Pre C++20, two iterators are better because they allow the function work on all types of iterators even those that don't know the size of the range. This is the convention most of the standard library follows.
Post C++20, you would probably use a range.
PS: Don't use recursion to calculate a sum. That's a bad idea. Use std::accumulate or at least a proper iterative loop.
I don't think one option is strictly better than the other, but the idiomatic approach in C++ is usually to use a pointer ("iterator") to the start and end of the container. Compare, e.g., with std::accumulate.
From a perspective on how they manage resources they are the same, so studying them from a time complexity point... they are the same too, the main difference on this to methods is how you obtain the size or the end pointer, but you only need to do it once, so the time it takes related to the size of the array will not change, cause is a single operation for the hole execution of the algorithm.
So calling them (when not having the size in a variable) looks like:
float value = summationArray(array, sizeof(array)/sizeof(array[0]));
float value = summationArray(array, std::end(array));
So I think, I would go with the end option, since it looks more """"pro""""", it's cleaner and is more c++ style.

Should .at() be used over [] in std::vector or std::array? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
This is related to this post that talked about .at() vs [] in std::vector. I just want to ask if .at() should be used over the bracket operators? Take the following code example:
#include <vector>
#include <iostream>
void print(const std::vector<int> &v)
{
for(int i = 0; i < v.size(); ++i)
{
std::cout << v.at(i) << " ";
}
std::cout << std::endl;
}
int main()
{
std::vector<int> test = {1,2,3,4};
print(test);
}
I would not print a vector this way, I would used for(const auto &e : v) and print out every element as that is guaranteed to not go outside the bounds of the vector. However let's say for a minute we are teaching new students about for loops.
Say we change the second argument in our for loop to v.size() + 1. .at(i) will crash and give us a meaningful runtime error std::out_of_range. However if we change .at(i) to be v[i] the program runs fine and prints out an extra number for me. I'm running this on Ubuntu 18.04 on Window's, I thought the program would crash when I did that however it didn't.
So the question stands, should we be using .at() instead of [] when accessing our containers?
Should .at() be used over [] in std::vector or std::array?
Yes, if
You are unable to prove that the index you access is within bounds.
You don't want to bother proving that.
You might make a mistake in your proof or in your implementation (for humans, this is "yes" most of the time), and undefined behaviour in your program is more costly than the overhead of at.
No, if
You cannot afford the overhead of at.
It doesn't matter much, if
Your program isn't used in situations where undefined behaviour could result in loss (or leaking) of information, anything of monetary value, life etc.
let's say for a minute we are teaching new students
Using at is particularly useful to new students whose ability to reason about the correctness of their program has not yet developed.
On the other hand, understanding undefined behaviour is also essential to C++ programmers, and vector subscript and its caveats need to also be introduced to students... at some later time when they are already comfortable with vectors.

One way swap for vectors, is it possible? [closed]

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 6 years ago.
Improve this question
In C++98, this is what I want to do (this does not work as _M_start, etc are private members):
void vectormove(std::vector<int>& a, std::vector<int>& b)
{
a._M_impl._M_start = b._M_impl._M_start;
a._M_impl._M_finish = b._M_impl._M_finish;
a._M_impl._M_end_of_storage = b._M_impl._M_end_of_storage;
}
This is how I want to call
//vectors are predefined already
std::vector<int> a;
std::vector<int> b(10000000,20);
//in later part of code
//a=b; //expensive copy
//std::swap(a,b); //inexpensive swap
vectormove(a,b); //i need an inexpensive one way swap instead
I may have butchered terminology by using copy, move and swap loosely, but I dont have a better grasp on this subject. I hope I was able to convey my intent.
It looks like you just want a to refer to b's internals. The way to do that is just:
std::vector<int>& a = b;
if you want a to take over b's internals, that's:
std::vector<int> a = std::move(b);
which in C++03 could be implemented as a swap with an empty vector:
std::vector<int> a;
using std::swap;
swap(a, b);
If your question is how to write a compilable implementation of your vectormove(), it's like this:
// NOT USEFUL CODE
void vectormove(std::vector<int>& a, std::vector<int>& b)
{
memcpy(&b, &a, sizeof(std::vector<int>));
}
But this is not useful, because once you've done this you are on the path to undefined behavior. Perhaps double-free, perhaps use-after-free, etc.
It seems like you would be best served either by the regular a.swap(b) or by storing a as type int* instead, like this:
std::vector<int> b(10000000,20);
std::pair<int*, int*> a(&b[0], &b[b.size()]);
Now you have an a which can be passed around cheaply and refers to the original vector. Just make sure you don't invalidate a by modifying b afterwards.

How to declare an operator overloading < to dynamically shift between class variables whenever needed? [closed]

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 5 years ago.
Improve this question
I've been searching lots of sites and browsed few books about this but failed to come across to find good sources about implementation of how to dynamically (within execution of the program) compare different datatypes in a class with less- < or , bigger than > operators.
Let's say we've the following snippet code:
#include <iostream>
using namespace std;
class OP
{
private:
string alias;
float locatorX;
int coordinate;
public:
bool operator<(const OP& rhs)
{
return (this->locatorX < rhs.locatorX);
//Here! How do I do to make the compiler understand that
//I compare i.e alias or coordinate whenever I need?
//I tried with:
return (this->coordinate < rhs.coordinate, this->alias < rhs.alias);
//But it didn't really do the trick when implemented
//a sort algorithm inside main as it failed to sort a string array.
}
};
EDIT:
Since most of the kind people here did not understand the question, here is a scenario which you hopefully get.
Let us say we want to create a map that accepts a string, int and float types. We create a function inside of the class OP that accepts all given datatypes and saves them in the created class array. And so we have i.e 15 records in our class array.
How do I do so that I can dynamically bubble sort (with help of < operator), alias (string) locatorX(float) and coordinate(int) (whichever I choose) in ascending order with less than operator?
For example I somewhat need to sort coordinates or alias (if needed) at run time. How do I do this?
Example output:
(First position in array):
"Albert street 5th"
Coordinate: 1691
locatorX: 19.52165
(Second position in array):
"Main street 7th alley"
Coordinate: 59
locatorX: 8175. 12
(Third position in array):
"Elm/Kentucky"
Coordinate: 9517
locatorX: 271.41
Typically you'd create a separate comparator for each comparison you wish to implement. You can't munge them into a single operator< and, although you could technically produce a different function that performed a different comparison depending on the value of some new, third argument, it would be incompatible with almost everything currently existing that knows how to work with comparators.
This is one of the scenarios in which operator overloading specifically is the wrong tool for the job.
There seems to be several ways to do so:
Switch between comparison functions at the call site
You have to define separate compare functions for different fields.
std::vector<Object> v;
enum class OrderBy
{
alias,
coordinate
}
OrderBy order_by = get_orderBy_from_user();
switch (order_by)
{
case OrderBy::alias:
std::sort(v.begin(), v.end(), compare_by_alias());
break;
case OrderBy::coordinate:
std::sort(v.begin(), v.end(), compare_by_coordinate());
break;
}
Make a choice inside a comparison function.
You must communicate the choice of ordering field somehow into the function.
The options are: global or singleton "configuration" object, member variable in the comparison class. I would avoid any globals, thus the second option:
struct compare_by_field
{
OrderBy order_by_;
compare_by_field(OrderBy order_by) : order_by_(order_by)
{}
bool operator()(const Object & lhs, const Object & rhs) const
{
switch (order_by_)
{
case OrderBy::alias:
return lhs.alias < rhs.alias;
case OrderBy::coordinate:
return lhs.coordinate < rhs.coordinate;
}
}
}
std::sort(v.begin(), v.end(), compare_by_field(get_order_by_from_user()));

Vector of vectors as efficient data structure; alternatives to std::vector<std::vector<someType>> [closed]

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 7 years ago.
Improve this question
I'm looking for data structure where I can stores multiple vectors in one vector without risking fragmentation or any performance issues.
Now doing this
std::vector< std::vector<SomeType> > myMultiVector;
would help, but for my understanding the memory gets fragmented because obviously every vector within myMultiVector will not lie in a contiguous space, because of its allocation scheme.
This is not for creating arrays where I know the dimensions or sizes from the start. The sizes are dynamic in all directions. What I want is a structure like that one, in which the allocated size is contiguous. I want to be able to do something like push_back() and resize() on the vector of vectors and every vector itself. The size of the vectors should be able to differ.
I have been taking a look at Boost::Multiarray. Seems promising, but don't want an array, I want something where dyanmic. I'm still not sure, though I can change sizes in the dimensions if it does that by an efficient way. So maybe Boost::Multiarray is the answer for that.
I also have been thinking about using std::multimap or even std::unordered_multimap and use the key as index, because of the interal sorting and hashing I'm not sure if it the right structure though the allocation space should be contiguous.
Using std::vector< std::vector > myMultiVector; works for what I need but I feel there is a missed oportunity for optimization.
What other Alternatives do you know which could help providing a more efficient vector of vectors? Let me know :-)
NOTE: I know the question is quite similar to others asked here. I'm only asking for alternatives not quite for the solution of a particular problem.
It sounds like the different things you want exclude each other. If you want to have a size-flexibility in each of the subvectors and at the same time have all the data nicely aligned in the memory you are basically forced to reallocate memory for all vectors and do a lot of copying each time you change the size of any of the subvectors. Thus probably it's a better idea to stay with the std::vector< std::vector<SomeType> >. If you need to do a lot of efficient operations with a fixed size of the vectors between every resize operation, you could think of creating an intermediate array into which you copy all your data.
You should also think about whether your concerns about performance have an effect in practice. Unless you notice that using std::vector< std::vector<SomeType> > does actually influence your performance significantly you should maybe not worry about it.
So to directly answer your question: I think there probably is no better data type for your needs, because the one you suggested is already totally fine.
If you're careful about using it, you could always implement a 1D vector as a 2D one using functors:
template <typename T>
class Vector2D : public std::vector<T>
{
protected:
unsigned _width;
public:
unsigned width() {return _width;}
void setWidth(unsigned i) {width = i;}
T& operator()(int x, int y) {
return this->operator[](x + _width * y);
}
Vector2D(unsigned newWidth = 10) : std::vector<T>(), _width(newWidth) {}
};
Which allows you to do things like:
int main() {
Vector2D<int> vec(10);
vec.resize(100, 0);
vec(6, 7) = 3;
int some_number = vec(6, 7);
cout << some_number: //Output: 3
}
The advantage of this approach is that the data is contiguous, yet can be manipulated with 2-dimensional semantics.
std::multimap / std::unordered_multimap will certainly not do what you want. Each individual SomeType will be in it's own allocation (much worse than a vector of vectors).
I don't think you will find a pre-built type that does what you want - you are going to have write it yourself (possibly by wrapping a single std::vector, and then providing smart iterators which understand the range of this particular vector). Note that my_magic.front().push_back(...) will have to insert into the middle of your backing vector, and shuffle everything up (although vector::insert will do the shuffling for you).
Personally, I would be surprised if it was worth it.
I would suggest using your own container. I am going to give you an abstract Idea:
class MyOwn2D{
MyOwn2D(int rows,int cols):rows(rows),cols(cols),data(std::vector<SomeType>(rows*cols){}
SomeType& get_element(int i,int j){
return data[i*rows+j];
}
private:
int rows,cols
std::vector<SomeType> data;
};
The previous example is so dummy. You need something much better with operators overloading and you may need a proxy to do [][] operator (to more like 2D array). So, I was just proposing the idea of it. Good Luck!