Is integer multiplication really done at the same speed as addition on a modern CPU?

后端 未结 11 752
梦谈多话
梦谈多话 2020-12-23 13:31

I hear this statement quite often, that multiplication on modern hardware is so optimized that it actually is at the same speed as addition. Is that true?

I never ca

11条回答
  •  情歌与酒
    2020-12-23 14:09

    A multiplication requires a final step of an addition of, at minimum, the same size of the number; so it will take longer than an addition. In decimal:

        123
        112
       ----
       +246  ----
       123      | matrix generation  
      123    ----
      -----
      13776 <---------------- Addition
    

    Same applies in binary, with a more elaborate reduction of the matrix.

    That said, reasons why they may take the same amount of time:

    1. To simplify the pipelined architecture, all regular instructions can be designed to take the same amount of cycles (exceptions are memory moves for instance, that depend on how long it takes to talk to external memory).
    2. Since the adder for the final step of the multiplier is just like the adder for an add instruction... why not use the same adder by skipping the matrix generation and reduction? If they use the same adder, then obviously they will take the same amount of time.

    Of course, there are more complex architectures where this is not the case, and you might obtain completely different values. You also have architectures that take several instructions in parallel when they don't depend on each other, and then you are a bit at the mercy of your compiler... and of the operating system.

    The only way to run this test rigorously you would have to run in assembly and without an operating system - otherwise there are too many variables.

提交回复
热议问题