Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Optimization on negative integers

Lets say we have a negative integer say int a;

is there a faster implementation of -a?

Do I have to do some bitwise operation on this?

like image 743
yoitsfrancis Avatar asked Aug 14 '26 08:08

yoitsfrancis


2 Answers

There's almost certainly nothing faster than the machine code NEG instruction that your compiler will most likely turn this into.

If there was, I'm sure the compiler would use it.

For a twos-complement number, you could NOT it and add 1 but that's almost certainly going to be slower. But I'm not entirely certain that the C/C++ standards mandate the use of twos-complement (they may, I haven't checked).

I think this question belongs with those that attempt to rewrite strcpy() et al to get more speed. Those people naively assume that the C library strcpy() isn't already heavily optimized by using special machine code instructions (rather than a simplistic loop that would be most people's first attempt).

Have you run performance tests which seem to indicate that your negations are taking an overly long time?

<subtle-humor-or-what-my-wife-calls-unfunny>

    A NEG on a 486 (state of the art the last time I had to worry about clock cycles) takes 3 clock cycles (memory version, register only takes 1) - I'm assuming the later chips will be similar. On a 3Ghz CPU, that means you can do 1 billion of these every second. Is that not fast enough?

</subtle-humor-or-what-my-wife-calls-unfunny>

like image 69
paxdiablo Avatar answered Aug 16 '26 22:08

paxdiablo


To clarify Pax's statement,

C++ compilers are not mandated to use two's complement, except in 1 case. When you convert a signed type to an unsigned type, if the number is negative, the result of the conversion must be the 2's complement representation of the integer.

In short, there is not a faster way than -a; even if there were, it would not be portable. Keep in mind as well that premature optimization is evil. Profile your code first and then work on the bottlenecks.

See The C++ Programming Language, 3rd Ed., section C.6.2.1.

like image 26
rlbond Avatar answered Aug 16 '26 21:08

rlbond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!