gpt4 book ai didi

c++ - 为什么内联函数的效率低于内置函数?

转载 作者:IT老高 更新时间:2023-10-28 21:38:09 26 4
gpt4 key购买 nike

我正在尝试关于 InterviewBit 中的数组的问题.在这个问题中,我创建了一个返回整数绝对值的内联函数。但有人告诉我,我的算法在提交时效率不高。但是当我改为使用 C++ 库中的 abs() 时,它给出了一个 正确答案 的结论。

这是我的函数得到了一个低效判决 -

inline int abs(int x){return x>0 ? x : -x;}

int Solution::coverPoints(vector<int> &X, vector<int> &Y) {
int l = X.size();
int i = 0;
int ans = 0;
while (i<l-1){
ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
i++;
}
return ans;
}

这是得到正确答案的那个 -

int Solution::coverPoints(vector<int> &X, vector<int> &Y) {
int l = X.size();
int i = 0;
int ans = 0;
while (i<l-1){
ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
i++;
}
return ans;
}

为什么会发生这种情况,因为我认为内联函数是最快的,因为没有调用?还是网站有错误?如果站点是正确的,C++ abs() 使用什么比 inline abs() 更快?

最佳答案

我不同意他们的判决。他们显然错误

在当前的优化编译器上,两种解决方案都会产生完全相同的输出。甚至,如果他们没有产生完全相同,他们会产生与库代码一样高效的代码(一切都匹配可能有点令人惊讶:算法,使用的寄存器。也许是因为实际的库实现是否与 OP 的相同?)。

正如其他答案所暗示的那样,没有理智的优化编译器会在您的 abs() 代码中创建分支(如果可以在没有分支的情况下完成)。如果编译器没有优化,那么它可能没有内联库abs(),所以它也不会很快。

优化 abs() 是编译器最容易做的事情之一(只需在窥视孔优化器中为其添加一个条目,然后完成)。

此外,我在过去看到过库实现,其中 abs() 被实现为非内联库函数(不过,这是很久以前的事了)。

两种实现方式相同的证明:

海合会:

myabs:
mov edx, edi ; argument passed in EDI by System V AMD64 calling convention
mov eax, edi
sar edx, 31
xor eax, edx
sub eax, edx
ret

libabs:
mov edx, edi ; argument passed in EDI by System V AMD64 calling convention
mov eax, edi
sar edx, 31
xor eax, edx
sub eax, edx
ret

clang :

myabs:
mov eax, edi ; argument passed in EDI by System V AMD64 calling convention
neg eax
cmovl eax, edi
ret

libabs:
mov eax, edi ; argument passed in EDI by System V AMD64 calling convention
neg eax
cmovl eax, edi
ret

Visual Studio (MSVC):

libabs:
mov eax, ecx ; argument passed in ECX by Windows 64-bit calling convention
cdq
xor eax, edx
sub eax, edx
ret 0

myabs:
mov eax, ecx ; argument passed in ECX by Windows 64-bit calling convention
cdq
xor eax, edx
sub eax, edx
ret 0

国际商会:

myabs:
mov eax, edi ; argument passed in EDI by System V AMD64 calling convention
cdq
xor edi, edx
sub edi, edx
mov eax, edi
ret

libabs:
mov eax, edi ; argument passed in EDI by System V AMD64 calling convention
cdq
xor edi, edx
sub edi, edx
mov eax, edi
ret

See for yourself在 Godbolt Compiler Explorer 上,您可以在其中检查各种编译器生成的机器代码。 (链接由 Peter Cordes 友情提供。)

关于c++ - 为什么内联函数的效率低于内置函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44994718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com