Addition operation versus multiplication operation

亡梦爱人 提交于 2019-12-24 16:46:29

问题


I know, that addition operation is more trivial than multiplication operation. But will there be any difference in execution time of 123456 * 3 and 123456 + 123456 + 123456?

How exactly works multiplication?

Do multiplication algorithms vary in different programming languages?

How multiplication looks on low-level (i.e. Assembler code)?


回答1:


In x86 assembly language the addition and multiplication operations look like this:

ADD [operand1], [operand2] where operand1 can be register, operand 2 can be register, constant or memory address It takes from 1 to 7 clocks depending on processor model and operand2 type

MUL [operand] ;for unsigned multiplication multiplies the content of the accumulator register (AL, AX, EAX) with operand, which can be a register or a memory address. And again, depending on the type of the operand and processor model, it takes 12-38 clocks There's also a version of MUL that does signed multiplication.

This is core assembly language, without modern SIMD extensions like SSE etc. The real speed, as mentioned above, depends on the compiler optimizations.

A smart compiler will most likely replace your 123456 + 123456 + 123456 with 3*123456




回答2:


Premature optimization is the root of all evil :)

What you give the compiler is not what you get back after the optimization step, so while in theory addition is faster, in real world conditions you can never be sure what will be the result (not to mention when you take into account the SSE or other processor instructions that the compiler might use).



来源:https://stackoverflow.com/questions/12569367/addition-operation-versus-multiplication-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!