fastest way to negate a number

后端 未结 7 1694
南旧
南旧 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:55

    Assuming the processor is at least somewhat competent and has sizeof(int) == sizeof(Cpu_register), then a "make this number negative" will be a single instruction (usually called neg) [well, may need the value loading and storing too, but if you are using the variable for anything else, it can remain after the load, and only be stored later one...]

    Multiplying by -1 is most likely slower than a = -a;, but most competent compilers should be able to make both of these equivalent.

    So, just write the code clearly, and the rest should take care of itself. Negating a number is not a difficult operation in most processors. If you are using some unusual processsor, then look at the compiler output, and see what it does.

    0 讨论(0)
提交回复
热议问题