当我所做的只是将循环代码移动到函数中时,代码运行速度慢十倍

Joh*_* Jo 5 c++ performance

我在运行下面的代码,基本上做的很少.它只增加2和4亿次并输出运行时.

#include "time.h"
#include <iostream>
using namespace std;

void add (){
int tot = 2+4;
}

void main(){
int t = clock();
int count = 0;
while(count<100000000){
    int tot = 2+4;
    count++;
}
cout <<endl<< "runtime = " << fixed <<(double) (clock() - t) / CLOCKS_PER_SEC <<"s" << endl;
Run Code Online (Sandbox Code Playgroud)

}

但是当我做同样的事情但是调用一个函数时,我有兴趣看到时差.所以我用"add()"替换了"int tot = 2 + 4"这一行.

我期待第二个运行时稍微长一点,但是要长一点.第一个实现= .3s和第二个实现= 3s.

我理解调用该函数需要使用堆栈来存储返回地址并存储本地数据.但它必须做得更多呢?

如果有人可以向我解释究竟是什么导致运行时间的巨大差异,或者我正在做些傻事,那将会很棒.

Jes*_*mos 5

正如Seth已经提到的,内联函数可能会得到优化.

在第一种情况下(基本优化)最有可能而不是不断添加这两个数字,它将解决2 + 4到6只是做一个简单的

mov eax, 6 ;eax is just an example here or
mov tot_addr, 6 ; mem->mem mov
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,因为它是系统必须的函数调用

push 4 ;assuming 4 byte ints
push 4 ;wrote 2 to be clear that you have to push both variables
call add
Run Code Online (Sandbox Code Playgroud)

或者沿着这些方向的东西.因为需要为该函数创建调用堆栈(为了简单起见,省略了返回值push等).一旦该函数返回,堆栈指针需要在第一次推送之前移回,然后RET将设置指令指针.正如你所看到的,这比做一个简单的更昂贵

mov eax, 4
add eax, 2
Run Code Online (Sandbox Code Playgroud)

如果你只做一个简单的(非优化的添加),这可能就是这种情况

编辑:这里有一些关于内嵌函数的更多信息.当你内联函数时,它只需要函数本身可以执行的任何功能,并将指令直接放在引用的位置,而不是执行CALL指令并直接设置函数调用.例如,而不是

mov eax, 4
mov ecx, 2
push 4 ; size for return value
push eax
push ecx
call add
Run Code Online (Sandbox Code Playgroud)

你最终会得到

mov eax, 4
mov exc, 2
add eax, ecx
Run Code Online (Sandbox Code Playgroud)

在代码方面:

int a = 4;
int b = 2;
int res = add(a, b);
Run Code Online (Sandbox Code Playgroud)

会成为

int a = 4;
int b = 2;
int res = a + b;
Run Code Online (Sandbox Code Playgroud)

假设您内联添加功能.