c++基础,内联函数,真正的代码内嵌

本章内容

1.内联函数的特性

2.内联函数的语法规则

3.内联函数的性能能测试

4.内联函数特性总结

5. 内联函数与宏定义的比较

 

1. 内联函数的特性

内联函数直接被嵌入到调用的位置,进而减小调用函数消耗的时间。但是消耗了更多的资源。因此对于函数中代码比较多的函数不宜使用内联函数,即使使用,系统也会自动将内联函数编译成普通函数。

2. 内联函数的语法规则

c++基础,内联函数,真正的代码内嵌
 

3. 内联函数的性能能测试

 

源码

#include <iostream>
#include <ctime>
#include <windows.h>


// 内联函数将函数体嵌入到主函数中,避免频繁的函数调用函数过程
inline int fun1(int a, int b) {
    int tem;
    tem = a > b ? a : b;
    return tem;
}

int fun2(int a, int b) {
    int tem;
    tem = a > b ? a : b;
    return tem;
}

int main()
{
    int a = 10, b = 20, c=0;
    int d=0;
    long int LEN = 100000000;

    DWORD time_start, time_end;
    time_start = GetTickCount(); //从操作系统启动经过的毫秒数
    // 内联函数测试
    for (long int i = 0; i < LEN; i++)
    {
        c = fun1(a, b);
    }
    time_end = GetTickCount();
    printf("内联函数测试: a=%d,b=%d,c=%d, time = %d ms\n", a, b, c, time_end - time_start);

    // 普通函数测试
    time_start = GetTickCount(); //从操作系统启动经过的毫秒数
    for (long int i = 0; i < LEN; i++)
    {
        c = fun2(a, b);
    }
    time_end = GetTickCount();
    printf("普通函数测试: a=%d,b=%d,c=%d, time = %d ms\n", a, b, c, time_end - time_start);

    
}
 

输出结果

c++基础,内联函数,真正的代码内嵌

没有发现性能获得优化

4.内联函数特性总结

c++基础,内联函数,真正的代码内嵌

c++基础,内联函数,真正的代码内嵌

5. 内联函数与宏定义的区别

内联函数在编译阶段将函数内嵌到主程序中。

宏定义在预处理阶段将代码内嵌到主程序中。

测试代码:

#define SQR(x) ((x)*(x))

inline int sqr(int x) { return x * x; };

int main()
{
    int a = 3, b = 3,c=3;

    printf("直接实现: ((x)*(x)) = %d\n", ((++c)*(++c)));

    printf("宏定义输出结果: SQR(a++) = %d\n", SQR(++a));

    printf("内联函数输出结果: sqr(b++) = %d\n", sqr(++b));
    printf("a = %d, b =%d\n", a, b);
}

输出结果:

c++基础,内联函数,真正的代码内嵌