C++中的内联与正常函数

fll*_*rbt 3 c++ inline function

我刚刚完成了Bruce Eckel的内联函数章节:用C++思考.那么有一个练习要求你创建两个精确的函数,一个是内联函数,另一个函数不是.然后使用clock()并计算每个传递的时间.我已经处理过类似的问题,我认为它没有任何复杂性.因此我想出了:

#include <iostream>
#include <ctime>
using namespace std;

inline int infun(int x) {
    x = 3;
    x = 5;
    cout << "";
    return x;

}

int fun(int x) {
    x = 3;
    x = 5;
    cout << "";
    return x;

}

int main() {

    clock_t startIn = clock();
    for (int i = 0; i < 10000000; i++) {
        infun(i);

    }
    clock_t finishIn = clock();

    clock_t start = clock();
    for (int i = 0; i < 10000000; i++) {
        fun(i);

    }
    clock_t finish = clock();

    clock_t startIn2 = clock();
    for (int i = 0; i < 10000000; i++) {
        infun(i);

    }
    clock_t finishIn2 = clock();

    cout << "Inline: " << (finishIn - startIn) << endl << "Regular Function: "
            << (finish - start) << endl<< "Second Inline: " << finishIn2 - startIn2 << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

产量

Inline: 195842
Regular Function: 166564
Second Inline: 162917
Run Code Online (Sandbox Code Playgroud)

所以我有3个功能.2个完全相似的内联和一个非内联(出于测试目的,我提出了这种情况).

a)为什么第一个内联占用所有时间(对于任何先执行的函数都会发生相同的情况)b)为什么如果重复减少(比方说1000),正常函数比其他函数更快.

即使使用更简单的功能,我的测试用例也很满意:

inline int infun(int x) {
    return x; 
}
Run Code Online (Sandbox Code Playgroud)

我还检查了程序集输出,以确保内联是真正的内联,或者g ++不会将非内联提升为内联.感谢您的时间,感谢任何反馈.

Ric*_*ges 5

从cppreference.com解释:

内联函数是具有以下属性的函数:

1)只要每个定义出现在不同的翻译单元中,程序中的内联函数可能有多个定义.例如,可以在多个源文件中#include'd的头文件中定义内联函数.

2)内联函数的定义必须存在于访问它的转换单元中(不一定在访问点之前).

3)具有外部链接的内联函数(例如,未声明为静态)具有以下附加属性:

1)必须在每个翻译单元中内联声明.2)每个翻译单元都有相同的地址.

请注意,并未提及或甚至暗示过机器代码的优化,性能或实际内联.

inline 简单地对编译器说:"这个函数可能被定义不止一次,但我保证每个定义都是相同的"