gpt4 book ai didi

c++ - 为什么 std::sin() 和 std::cos() 比 sin() 和 cos() 慢?

转载 作者:IT老高 更新时间:2023-10-28 21:51:20 43 4
gpt4 key购买 nike

测试代码:

#include <cmath>
#include <cstdio>

const int N = 4096;
const float PI = 3.1415926535897932384626;

float cosine[N][N];
float sine[N][N];

int main() {
printf("a\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cosine[i][j] = cos(i*j*2*PI/N);
sine[i][j] = sin(-i*j*2*PI/N);
}
}
printf("b\n");
}

时间到了:

$ g++ main.cc -o main
$ time ./main
a
b

real 0m1.406s
user 0m1.370s
sys 0m0.030s

添加using namespace std;后,时间为:

$ g++ main.cc -o main
$ time ./main
a
b

real 0m8.743s
user 0m8.680s
sys 0m0.030s

编译器:

$ g++ --version
g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2

组装:

Dump of assembler code for function sin@plt:                                    
0x0000000000400500 <+0>: jmpq *0x200b12(%rip) # 0x601018 <_GLOBAL_OFFSET_TABLE_+48>
0x0000000000400506 <+6>: pushq $0x3
0x000000000040050b <+11>: jmpq 0x4004c0
End of assembler dump.

Dump of assembler code for function std::sin(float):
0x0000000000400702 <+0>: push %rbp
0x0000000000400703 <+1>: mov %rsp,%rbp
0x0000000000400706 <+4>: sub $0x10,%rsp
0x000000000040070a <+8>: movss %xmm0,-0x4(%rbp)
0x000000000040070f <+13>: movss -0x4(%rbp),%xmm0
0x0000000000400714 <+18>: callq 0x400500 <sinf@plt>
0x0000000000400719 <+23>: leaveq
0x000000000040071a <+24>: retq
End of assembler dump.

Dump of assembler code for function sinf@plt:
0x0000000000400500 <+0>: jmpq *0x200b12(%rip) # 0x601018 <_GLOBAL_OFFSET_TABLE_+48>
0x0000000000400506 <+6>: pushq $0x3
0x000000000040050b <+11>: jmpq 0x4004c0
End of assembler dump.

最佳答案

您正在使用不同的重载:

试试

        double angle = i*j*2*PI/N;
cosine[i][j] = cos(angle);
sine[i][j] = sin(angle);

无论是否使用 using namespace std;

,它都应该执行相同的操作

关于c++ - 为什么 std::sin() 和 std::cos() 比 sin() 和 cos() 慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6976458/

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