Several tips for efficient C Programming

Source: Internet
Author: User
Several tips for efficient C Programming
Huazhong University of Science and Technology Ding Xue

Write efficient and concise C Language Code Is the goal pursued by many software engineers. This article provides some experiences and experiences
I would like to advise you on any mistakes.

1st tips: Change the time by Space

ComputerProgramThe biggest contradiction in the process is the contradiction between space and time. From this perspective, we will reverse thinking to consider the program.
For efficiency issues, we have a 1st strategy to solve the problem-change the space for time.

For example, assign a value to a string.

Method:

# Define Len 32

Char string1 [Len];

Memset (string1, 0, Len );

Strcpy (string1, "This is an example !! "
Method B:

Const char string2 [Len] = "this is an example! "

Char * CP;

CP = string2;

(You can directly use a pointer to perform operations .)

From the above example, we can see that the efficiency of A and B is incomparable. In the same bucket, B directly uses the pointer
Yes, but a needs to call two character functions. B's disadvantage is that flexibility is not as good as. In the frequency
When changing the content of a string, A has better flexibility. If Method B is used, many characters need to be reserved.
String, which occupies a large amount of memory, but achieves high efficiency in program execution.

If the system has high real-time requirements and memory requirements, I recommend that you use this method.

The edge action of this trick-using a macro function instead of a function. Example:

Method C:

# Define bwmcr2_address 4

# Define bsmcdr2_address 17

Int bit_mask (int_bf)

{

Return (IU <(BW ##_ BF)-1) <(BS ##_ BF );

}

Void set_bits (int_dst, int_bf, int_val)

{

_ DST = (_ DST )&~ (Bit_mask (_ BF) I \ (_ Val) <(BS ##_ BF) & (bit_mask (_ BF )))

}

Set_bits (mcr2, mcr2_address, registernumber );
Method d:

# Define bwmcr2_address 4

# Define bsmcdr2_address 17

# Define bmmcdr2_address bit_mask (mcdr2_address)

# Define bit_mask (_ BF) (1u <(BW ##_ BF)-1) <(BS ##_ BF)

# Define set_bits (_ DST, _ BF, _ Val) \ (_ DST) = (_ DST )&~ (Bit_mask (_ BF) I (_ Val) <
(BS # _ BF) & (bit_mask (_ BF ))))

Set_bits (mcr2, mcr2_address, registernumber );

The difference between a function and a macro function is that a macro function occupies a large amount of space while a function occupies time. What you need to know
Yes, function calling uses the system stack to store data. If the compiler has the stack check option
Some Assembly statements are embedded in the header to check the current stack. At the same time, the CPU also needs to save and restore the current
On-site pressure stack and elastic stack operations, so function calling takes some CPU time. The Macro function does not have this question.
Question. Macro functions are only embedded into the current program as pre-written code and do not generate function calls. Therefore, they only occupy
This phenomenon is particularly prominent when the same macro function is frequently called.

The D method is the best position operation function I have seen. It is part of arm's source code and has been implemented in just three lines.
Multiple Functions, covering almost all bit operation functions. The C method is its variant, and the taste needs to be carefully understood.

2nd tips: mathematical methods to solve problems

Now we assume the second trick of writing efficient C language-using mathematical methods to solve the problem.

Mathematics is the mother of computers. Without the foundation and foundation of mathematics, there will be no computer development.
When using some mathematical methods, the execution efficiency of the program will be improved by an order of magnitude.

For example, 1 ~ Sum of 100.

Method E

Int I, J;

For (I = 1; I <= 100; I ++ ){

J + = I;

}
Method F

Int I;

I = (100*(1 + 100)/2

This example is one of my most impressive mathematical examples. It was tested by my computer beginner. At that time, I only had primary school.
It's a pity that I didn't know how to use formula NX (n + 1)/2 to solve this problem. Method E is used to solve the problem after 100 cycles.
That is to say, at least 100 assignments, 100 judgments, and 200 additions (I and j) are used. Method F only uses one addition.
Method, one multiplication, and one division. The effect is self-evident. So now, when I compile the program, I am more confused.
To maximize the power of mathematics to improve the efficiency of program running.

3rd tips: Bit operations

The third way to achieve efficient C language writing is to use bitwise operations to reduce division and modulo operations.

In computer programs, the bit of data is the smallest unit of data that can be operated. Theoretically, the bit operation can be used to complete
Some operations and operations. Generally, bitwise operations are used to control hardware or perform data transformation. However, flexible bitwise operations
Operations can effectively improve the program running efficiency. Example:

Method g

Int I, J;

I = 257/8;

J = 456% 32;
Method H

Int I, J;

I = 257> 3;

J = 456-(456> 4 <4 );

Literally, it seems that H is much more troublesome than G. However, if you carefully check the generated assembly code, you will understand that the method gcall uses the basis
The current modulo and Division functions involve both function calls and many Assembly codes and registers. The method H
The code is simpler and more efficient. Of course, due to different compilers
The difference is not big. However, from the perspective of Ms C and arm C, the efficiency gap is not small. Relevant assembly code
It is not listed here.

When using this method, you must note that the CPU usage is different. For example, the process written using this method on a PC
And it passes debugging on the PC. When it is transplanted to a 16-bit platform, it may cause code risks. So only
This offer can be used only on the basis of certain advanced technologies.

4th tips: Assembly embedding

The fourth measure is embedded assembly.

"In the eyes of people familiar with assembly languages, C-language programs are junk ". This statement is somewhat radical,
Yes, but it does. Assembly language is the most efficient computer language, but it cannot be used to write an operating system.
OK? Therefore, to achieve program efficiency, we had to adopt a flexible method-Embedded Assembly, mixed programming.

For example, assign array 1 to array 2, and each byte must be consistent. Char string1 [1024],
String2 [1024];

Method I

Int I;

For (I = 0; I <1024; I ++)

* (String2 + I) = * (string1 + I)
Method J

# Int I;

For (I = 0; I <1024; I ++)

* (String2 + I) = * (string1 + I );

# Else

# Ifdef_arm _

_ ASM

{

MoV r0, string1

MoV R1, string2

MoV R2, #0

Loop:

Ldmia R0 !, R3-R11

Stmia R1 !, R3-R11

Add R2, R2, #8

CMP R2, #400

BNE Loop

}

# Endif

Method I is the most common method and uses 1024 cycles. Method J is differentiated based on the platform.
The same operation is completed with only 128 cycles of Embedded Assembly. Some may say, why not use standard
What about the memory copy function? This is because the source data may contain 0 bytes of data. In this case, the standard library function will
The operation we requested will not be completed. This routine is typically used to copy LCD data. Varies
CPU, skilled in using the corresponding Embedded Assembly, can greatly improve the efficiency of program execution.

Although it is mandatory, it will be costly to use it easily. This is because the use of Embedded Assembly restricts
The portability of the program, so that the program in the Process of transplantation on different platforms, Crouching Tiger, Hidden Dragon, danger! In addition
It is contrary to the idea of modern software engineering and can be used only when it is forced. Remember.

I use C language for efficient programming. This article has been introduced here.
Discussion. I hope you can give us a better way to improve our programming skills.


from "Application of Single Chip Microcomputer and embedded system" 2003.9

Related Article

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.