Learn point C language (39): function

Source: Internet
Author: User
Tags include printf

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"

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.