Duff equipment is a very ingenious, seemingly very strange C code, it can greatly improve the efficiency of the execution of the program (this article will be tested), the source of Duff equipment I will not say, let us analyze.
The duff device takes into account that we typically use a for or while loop, and if the loop content itself does not take much time, then the time will be consumed primarily on the comparison statement of each loop.
In fact, the comparison statement is a great space for optimization, assuming you want to cycle 1000 times, the result you from the first start on the continuous comparison of whether to reach the upper bound, this is very futile.
Dave, this guy. The duff device was designed using the drop behavior of the switch statement.
We use the DAF device to calculate an accumulative operation that accumulates many times and compares it with the traditional while loop.
Test the main function
Duff Equipment:
Execution Time:
Its execution time is 0.496s. It should be noted here that the definition of X is to use the Register keyword, so that the CPU will put x as far as possible into the internal CPU registers, but is not fully stored in the register, because the computer General Register of ten or twenty (now 64 new CPU I do not know how many, but certainly very few), So the CPU just as much as possible for you to put X into the register.
Now let's look at the execution time of the traditional loop:
Test function:
Traditional methods:
Results:
As a result, Duff equipment did shorten a lot of time.
Of course, Duff devices can also use a for statement
Duff equipment (Duff's device)