gpt4 book ai didi

c - 在 if else 的每种情况下返回会更快/使用更少的内存吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:49 24 4
gpt4 key购买 nike

最近我在我的 CS 研究中得到了一个代码示例(参见代码 #1),我试图弄清楚我的第二个版本的代码是否会更快或使用更少的内存。你能回答我的问题吗?

// Code #1
double f(double b, double x)
{
double s;
if (x == 0.0)
s = 1.0;
else
s = sin(x)/x;
return s + b;
}

// Code #2
double f(double b, double x)
{
// I thought this would be faster and using less memory due to
// not declaring a new double
if (x == 0.0)
return 1.0 + b;
else
return sin(x)/x + b;
}

谢谢大家的帮助。

最佳答案

我已经生成了两种情况的集合。

案例一:

        push    rbp
mov rbp, rsp
sub rsp, 48
movsd QWORD PTR [rbp-24], xmm0
movsd QWORD PTR [rbp-32], xmm1
pxor xmm0, xmm0
ucomisd xmm0, QWORD PTR [rbp-32]
jp .L2
pxor xmm0, xmm0
ucomisd xmm0, QWORD PTR [rbp-32]
jne .L2
movsd xmm0, QWORD PTR .LC1[rip]
movsd QWORD PTR [rbp-8], xmm0
jmp .L4
.L2:
mov rax, QWORD PTR [rbp-32]
mov QWORD PTR [rbp-40], rax
movsd xmm0, QWORD PTR [rbp-40]
call sin
divsd xmm0, QWORD PTR [rbp-32]
movsd QWORD PTR [rbp-8], xmm0
.L4:
movsd xmm0, QWORD PTR [rbp-8]
addsd xmm0, QWORD PTR [rbp-24]
leave
ret
.LC1:
.long 0
.long 1072693248

案例 2:

        push    rbp
mov rbp, rsp
sub rsp, 32
movsd QWORD PTR [rbp-8], xmm0
movsd QWORD PTR [rbp-16], xmm1
pxor xmm0, xmm0
ucomisd xmm0, QWORD PTR [rbp-16]
jp .L2
pxor xmm0, xmm0
ucomisd xmm0, QWORD PTR [rbp-16]
jne .L2
movsd xmm1, QWORD PTR [rbp-8]
movsd xmm0, QWORD PTR .LC1[rip]
addsd xmm0, xmm1
jmp .L4
.L2:
mov rax, QWORD PTR [rbp-16]
mov QWORD PTR [rbp-24], rax
movsd xmm0, QWORD PTR [rbp-24]
call sin
divsd xmm0, QWORD PTR [rbp-16]
addsd xmm0, QWORD PTR [rbp-8]
.L4:
leave
ret
.LC1:
.long 0
.long 1072693248

没有区别。因此,它们之间没有速度优化。因此,代码优化取决于编译器。

关于c - 在 if else 的每种情况下返回会更快/使用更少的内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47133348/

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