How does Duff's device work?

前端 未结 11 1897
日久生厌
日久生厌 2020-11-22 04:56

I\'ve read the article on Wikipedia on the Duff\'s device, and I don\'t get it. I am really interested, but I\'ve read the explanation there a couple of times and I still do

11条回答
  •  余生分开走
    2020-11-22 05:37

    1: Duffs device is a particular implementation of loop unrolling. Loop unrolling is an optimisation technique applicable if you have an operation to perform N times in a loop - you can trade program size for speed by executing the loop N/n times and then in the loop inlining (unrolling) the loop code n times e.g. replacing:

    for (int i=0; i

    with

    for (int i=0; i

    Which works great if N % n == 0 - no need for Duff! If that is not true then you have to handle the remainder - which is a pain.

    2: How does Duffs device differ from this standard loop unrolling?
    Duffs device is just a clever way of dealing with the remainder loop cycles when N % n != 0. The whole do / while executes N / n number of times as per standard loop unrolling (because the case 0 applies). On the last first run through the loop the case kicks in and we run the loop code the 'remainder' number of times - the remaining runs through the loop run 'normally'.

提交回复
热议问题