C language can not be separated from functions, the use of functions is also very convenient, but the use of functions have a price;
Especially in the repeated call, the function will be repeatedly pressure stack, out of the stack and waste some time.
Here is the test, using the function and the time is no function: 8 seconds, 4 seconds!
1. Test the cost of using the function:
#include <stdio.h>
#include <time.h>
int sum(int x) {
return x + x;
}
int main(void)
{
int count = 1000000000;
int i;
int num;
time_t start, stop;
time(&start);
for (i = 0; i < count; i++) num = sum(i);
time(&stop);
printf("调函数用时: %d 秒;\n", stop - start); /* 8 */
time(&start);
for (i = 0; i < count; i++) num = i + i;
time(&stop);
printf("非函数用时: %d 秒;\n", stop - start); /* 4 */
getchar();
return 0;
}
2. Use inline functions:
The inline keyword is the inline function on the crown of the function head.
By using inline functions, you can optimize the function by embedding the function in the current position.
It is generally only possible to consider the use of a smaller function inline, since this is only a request, and the compiler does not guarantee that all applications are performed inline.
Inline functions can only use cells that are defined (rather than declared).
The example above continues to be used (only one inline) test is added.
Tested several times, the basic or the above test results; It seems that C++builder 2009 did not heed it.
#include <stdio.h>
inline int sum(int x) {
return x + x;
}
int main(void)
{
int count = 1000000000;
int i;
int num;
time_t start, stop;
time(&start);
for (i = 0; i < count; i++) num = sum(i);
time(&stop);
printf("调函数用时: %d 秒;\n", stop - start);
time(&start);
for (i = 0; i < count; i++) num = i + i;
time(&stop);
printf("非函数用时: %d 秒;\n", stop - start);
getchar();
return 0;
}
Back to "Learn point C-Directory"