Duff equipment (Duff's device)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.