Shift operator fast or not fast? [closed] - c++

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 9 years ago.
Improve this question
What is the faster between the two following code? why?
In which case one can be preferred to the other?
double x = (a + b) >> 1
double x = (a + b) / 2.0

These do different things so pick the one with the functionality you like: Truncating the result down or returning the 0.5 fraction.

"Premature optimization is root of all evil". Use what is more readable, when you have perfomance issue first look for algorithms and data structures, where you can get most perfomance gain, then run profiler and optimize where is necessary.

As others have said, the two statements produce different results, especially if (a + b) is an odd value.
Also, according to the language, a and b must be integral values in order to satisfy the shifting operation.
If a and b differ in type between the two statements, you are comparing apples to elephants.
Given this demo program:
#include <iostream>
#include <cstdlib>
#include <cmath>
using std::cout;
using std::endl;
int main(void)
{
const unsigned int a = 5;
const unsigned int b = 8;
double x = (a + b) >> 1;
cout << x << endl;
double y = (a + b) / 2.0;
cout << y << endl;
return EXIT_SUCCESS;
}
The output:
6
6.5
Based on this experiment, the comparison is apples to oranges. The statement involving shifting is a different operation that dividing by a floating point number.
As far as speed goes, the second statement is slower because the expression (a + b) must be converted to double before applying the division. The division is floating point, which may be slow on platforms without hardware floating point support.
You should not concern yourself on the execution speed of either statement. Of more importance is the correctness and robustness of the program. For example, the two statements above provide different results, which is a very important concern for correctness.
Most Users would wait for a program to produce correct results than have a quick program producing incorrect results or behavior (nobody is in a hurry for a program to crash).
Management would rather you spend time completing the program than wasting time optimizing portions of the program that are executed infrequently.

If a or b is a double or float, shifting will produce incorrect results.

Related

Most efficient way to find the greatest number not greater than A, which is divisible by B [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
I have 2 numbers A and B. I want to find C = A - (A % B), but there are some problems. First of all, if C and D = A / B should have the same parity ((even and even) or (odd and odd)), otherwise C should be incremented (++C). The second problem is that I constantly do this calculation, so I want the cost of it to be as small as possible. Right now my solution looks like this:
uint32_t D = A / B;
C = D * B;
if ((C ^ D) & 0x1) ++C;
Is there a better way to do this? Maybe (C % 2) != (D % 2) is faster because of compiler optimizations, but I can't proof it. I would also like to know if it can be done with some specific intel functions (registers).
I assume the inputs A and B are also uint32_t?
The cost of the division dwarfs everything else, unless B is known at compile time after inlining. (Even if it's not a power of 2). The actual div instruction is very expensive compared to anything else, and can't vectorize with SIMD. (The only SIMD division available on x86 is FP, or of course integer shifts for division by 2).
By far the most useful thing you could do is arrange for B's value to be visible to the compiler at compile time, or at least with link-time optimization for cross-file inlining. (Why does GCC use multiplication by a strange number in implementing integer division?)
If B isn't a compile-time constant, x86 division will produce the remainder for free, along with the quotient. sub is cheaper than imul, so use and let the compiler optimize:
uint32_t D = A / B;
uint32_t C = A - A % B;
And if B is a compile-time constant, the compiler will optimize it to a divide then multiply anyway and (hopefully) optimize this down to as good as you'd get with your original.
And no, (C^D) ^ 1 should be a more efficient way to check that the low bits differ than (C % 2) != (D % 2). Doing something separate to each input before combining would cost more instructions, so it's better to lead the compiler in the direction of the more efficient asm implementation. (Obviously it's a good idea to have a look at the asm output for both cases).
Possibly useful would be to use + instead of ^. XOR = Addition without carry, but you only care about the low bit. The low bit of ^ and + is always the same. This gives the compiler the option of using an lea instruction to copy-and-add. (Probably not helpful in this case; it's ok if the compiler destroys the
value in the register holding D, assuming it's dead after this. But if you also use D directly)
Of course, you don't actually want to branch with if(...) so you should write it as:
C += (C+D) & 1; // +1 if low bits differ

Order of operations not correct? (C++) [closed]

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
I was writing a small Least common multiple algorithm and encountered something I don't understand. This is the first and last part of the code:
long a = 14159572;
long b = 63967072;
int rest = 4;
long long ans;
.
. // Some other code here that is not very interesting.
.
else
{
//This appears correct, prints out correct answer.
ans = b/rest;
std::cout << a*ans;
}
But if I change the last "else" to this it gives an answer that is much smaller and incorrect:
else
{
std::cout << a*(b/rest);
}
Anyone know why this is? I don't think it's an overflow since it was no negative number that came out wrong, but rather just a much smaller integer (around 6*10^8) than the actual answer (around 2.2*10^14). As far as I understand it should calculate "b/rest" first in both cases, so the answers shouldn't differ?
Difference is not order of operations but data types:
ans = b/rest; // b/rest is long which upscaled to long long
std::cout << a*ans; // a converted to long long and result is long long
vs:
std::cout << a*(b/rest); // a*(b/rest) all calculations in long
so if you change your second variant to:
std::cout << a*static_cast<long long>(b/rest);
you should see the same result.
Update to why your cast did not work, note the difference:
long a,b;
// divide `long` by `long` and upscale result to `long long`
std::cout << static_cast<long long>( a / b );
// upscale both arguments to `long long` and divide `long long` by `long long`
std::cout << a / static_cast<long long>( b );
You're still encountering overflow. Just because you're not observing a negative number doesn't mean there's no overflow.
In your case specifically, long is almost certainly a 32-bit integer, as opposed to long long which is probably a 64-bit integer.
Since the maximum value of a 32-bit signed integer is roughly 2 billion, 14159572 * (63967072 / 4) is most definitely overflowing the range.
Make sure you perform your calculations using long long numbers, or else reconsider your code to avoid overflow in the first place.
The compiler assumes data types for each operand of your math equation and does the multiplication and division according to those assumed data types (refer to "integer division"). This also applies to intermediates of the computation. This also applies to the result passed to the stream since you don't pass a variable of an explicitly defined type.

Defining variables vs calculating on the fly [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 8 years ago.
Improve this question
In terms of readability and memory usage/ processing speed is it better to define a variable, modify it and output the variable or to just output a result? eg:
int a = 1, b = 2, c;
c = a+b;
std::cout << c << std::endl;
vs
int a = 1, b = 2;
std::cout << a+b << std::endl;
Thanks
Well with this example processing speed and space is negligible. So small and so few instructions.
But in the grand scheme of things the answer is -- well it depends.
The term "better" is in the eye of the beholder. What is better for one program might not be better for another (this includes readability). What may work in one instance may not work in another. Or in the end it could be negligible (arithmetic instructions are pretty fast depending on the scope of what you need and int, double, char, float data types are relatively small and well defined so you know how much memory you are taking up).
Here you do not define if these variables were declared on the stack or the heap. If on the stack then it doesn't matter if you declared it because after the function that these variables live in ends, the memory gets released. If on the heap you may not want to declare millions of variables just to sit there. But then again you may need them there.
So its based almost entirely on a case by case bases when dealing with bigger projects.
And you tell me what is better here?
int result = (3434*234+3423-4/3*23< 233+5435*234+342)? (int)(234+234+234234/34):(int)(2+3*234);
std::cout << result << std::endl;
OR
double x = 3434*234+3423-4/3*23;
double y = 233+5435*234+342;
double a = 234+234+234234/34;
double b = 2+3*234;
int result = 0;
if( x>y) result = a;
else result = b;
std::cout << result << std::endl;
in the end it these do the same things are the same with negligble difference but which one is easier to read?
Your question on memory is easy to answer, variables are stored identifiers so each take a couple bytes (bytes store 8 bits or binary digits) to store. That being said, a byte is almost no memory, meaning that ultimately it has no net effect. In terms of RAM (or Random Access Memory) a byte is again, almost negligible meaning that defining a, b, and c is barely slower than just calculating a + b. Makes sense?

Which of the two programs is better and why? [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 8 years ago.
Improve this question
Code 1
int A, B, MAX;
cout << "Give two numbers:" << endl;
cin >> A >> B;
if (A > B)
{
MAX = A;
}
else
{
MAX = B;
}
cout << "Largest amongst given numbers is: ";
cout << MAX << endl;
return 0;
Code 2
int A, B, MAX;
cout << "Give two numbers:" << endl;
cin >> A >> B;
MAX = A;
if (B > MAX)
{
MAX = B;
}
cout << "Largest amongst given numbers is: ";
cout << MAX << endl;
return 0;
In above program logic, which one is best and why? is there any difference between them.? it is my exam question i would like to ask stack overflow to know best opinion.
MAX = std::max(A, B);
Is better than both in terms of clarity.
In terms of speed, the compiler should be able to optimise any of these methods to be equivalent; but again I'd favour std::max because I'd sooner trust the compiler to optimise a standard function than some arbitrary made up code to perform the same task.
They are the same so I would prefer code 1 because it's more readable. In both cases you have to bring both A and B into a register (regardless) and then do a single comparison (regardless). And it won't write out to the variable MAX until after this segment is done (because it won't need to kick anything out of a register).
This isn't something that is going to cause any kind of performance gain. In fact, it's possible (although I doubt it) that the compiler would compile them the same (the compiler does all kinds of code modification to create an optimal set of instructions).
As suggested the only thing that likely would give a performance gain is using the library function std::max. This is because the compiler will basically perform the comparison in the most efficient way (likely without even calling a conditional jump). If your two values are integers, then you can see here that it's possible to find the max with five integer operations (all of which, except the multiplication can generally be done in a single cycle). You generally want to avoid conditional jumps as much as possible and this algorithm does that. Most likely the max function does something like this or similar (but it would have to be different for floating point values).
After MAX = std::max(A,B), the next best code is:
MAX = A > B ? A : B;
If you don't want to use that, then I prefer your "code 1" because:
code 2 always sets MAX = A, which is momentarily misleading and only becomes clear as the later code is studied; while this issue is common in C++ and many other languages, there's no particular reason to embrace that complication when it's easily avoided
for some types (the question didn't originally specify int), an assignment may be an expensive operation (e.g. copying a lot of data), so always assigning once is better than potentially assigning twice
For both those reasons, it also desirable to declare and define MAX in one step. It may not be practical if say it's a non-const reference accepted as a function argument, but when it is possible it's another good reason to prefer std::max or the ternary ? approach: you won't need a misleading and potentially inefficient or unavailable default construction. (Now you've changed the question to be int specific, the expense of copying and construction is known and trivial, and the optimiser can be counted on to remove them in most cases).
I would say use code 2. It is better because you explicitly say that if MAX B is greater than MAX A, then change MAX to B. In the other one, you don't have any defining factors about why MAX A is greater than MAX B. From what I see, you will probably have a harder time using code 1 than code 2.

Translating data from one type to another in C++? [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 9 years ago.
Improve this question
I wanted to understand how type conversion happens in a professional grade software?
Consider the following conversions:
int to double
double to int
string to double
double to string
Currently I am using Qt for my project, which has API for doing these tasks.
So I just wanted to know how people perform these conversions with standard C++ only.
Accuracy, speed & memory are the priorities in their respective order.
For int to double you can simply do static_cast<double>(int_value);
from double to int it depends on the case , most of the time static_cast would do , however, sometimes you need to have specific control over the value being rounded to int. For this you can use functions like floor, round , or ceil.
For string to anything and anything to string there are a couple of options:
snprintf() - not recommended unless you know what you are doing. accuracy is hard to control
stringstream / istringstream - this has good accuracy and easy to controll
boost::format - personal favorite, check doc: http://www.boost.org/doc/libs/1_53_0/libs/format/doc/format.html
In terms of performance it depends i would pick snprintf to be the fastest in certain cases since it does not require allocations.
The first one is often implicit (since it's a promotion). The first and the second one can be accomplished with a simple static_cast:
double x = 0.123;
int y = 123;
std::cout << static_cast<int>(x) << '\n';
std::cout << static_cast<double>(y) << '\n';
The third one would require a std::istringstream:
std::string x = "123.456";
double y;
std::istringstream ss(x);
ss >> y;
The fourth would require a std::stringstream:
double x = 123.456;
std::stringstream ss;
ss << x;
ss.str(); // your string
int to double is a promotion in C++, which can be done implicitly.
double to int can also be done implicitly but it should be use with caution since many doubles either don't represent round integral values or are too big to be converted. Most compilers warn about that loss of precision, so the cast should be made explicit to get rid of the warning - if you are sure you are doing the right thing.
string to double, double to string: These are normally used only for input/output (GUI, console, textfiles, ...). Numerical values should be handled inside the program as such and not as strings. You should prevent double->string->double conversion chains inside your program when possible, since both conversions are not accurate and prone to rounding and other errors.