fastest way to negate a number

后端 未结 7 1747
南旧
南旧 2020-12-29 03:20

I was thinking this morning here, what would be the fastest way to reverse a number of positive to negative and from negative to positive, of course, the simplest way might

7条回答
  •  孤独总比滥情好
    2020-12-29 03:38

    The other answers have correctly indicated that readability matters more:

    • You should forget about speed and choose the idiom that you find most readable.
    • Almost all compilers (with optimizations enabled) generate equivalent optimal code (probably a single instruction) for anything like a = -a, a *= -1 etc.1
    • Any attempt to make it faster will make it far less readable and could easily make it slower.
    • If you need to optimise, you should start by analysing generated code and performance.


    There is however a practical advantage to the *= -1 idiom: you only have to write the left hand side once, it is only evaluated once – and the reader only has to read it once! This is relevant when the LHS is long, complex or expensive or may have side-effects:

    (valid ? a : b)[prime_after(i++)] *= -1;
    *look_up (input) *= -1;  // Where look_up may have side-effects
    parity[state][(unsigned int)getc(stdin)] *= -1;
    variable_with_a_long_explanatory_name *= -1;
    

    And once one has adopted an idiom, one tends to stick with it in other situations.


    1 Observations by Peter Cordes: Almost all compilers understand that a = -a and a *= -1 are exactly the same and will emit whatever asm they decide will be most efficient on the target CPU, regardless of how you write it. (e.g. Godbolt compiler explorer for x86 gcc/MSVC/clang, and ARM gcc.) But though MSVS 2012 (in debug mode only) uses one instruction for each, they take 1 cycle for = -a and 3 for *= -1 on recent Intel CPUs, using an actual imul instruction.

提交回复
热议问题