为A + = B比在C = A + B更有效?

编程入门 行业动态 更新时间:2024-10-19 19:28:45
本文介绍了为A + = B比在C = A + B更有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道在一些语言如下:

I know in some languages the following:

a += b

的效率比:

a = a + b

,因为它消除了对创建临时变量的需要。这是在C的情况下?它是更有效地使用+ =(因此也 - = * = 等)

推荐答案

所以这里有一个明确的答案......

So here's a definitive answer...

$ cat junk1.c #include <stdio.h> int main() { long a, s = 0; for (a = 0; a < 1000000000; a++) { s = s + a * a; } printf("Final sum: %ld\n", s); } michael@isolde:~/junk$ cat junk2.c #include <stdio.h> int main() { long a, s = 0; for (a = 0; a < 1000000000; a++) { s += a * a; } printf("Final sum: %ld\n", s); } michael@isolde:~/junk$ for a in *.c ; do gcc -O3 -o ${a%.c} $a ; done michael@isolde:~/junk$ time ./junk1 Final sum: 3338615082255021824 real 0m2.188s user 0m2.120s sys 0m0.000s michael@isolde:~/junk$ time ./junk2 Final sum: 3338615082255021824 real 0m2.179s user 0m2.120s sys 0m0.000s

...对于我计算机和我编译器上运行的我操作系统。结果可以或可以不变化。在我系统,但是,时间是相同的:用户时间2.120s

...for my computer and my compiler running on my operating system. Your results may or may not vary. On my system, however, the time is identical: user time 2.120s.

现在只是给你看pressive现代编译器如何IM就可以了,你会注意到,我使用了前pression 在A * A 分配。这是因为这个小问题:

Now just to show you how impressive modern compilers can be, you'll note that I used the expression a * a in the assignment. This is because of this little problem:

$ cat junk.c #include <stdio.h> int main() { long a, s = 0; for (a = 0; a < 1000000000; a++) { s = s + a; } printf("Final sum: %ld\n", s); } michael@isolde:~/junk$ gcc -O3 -S junk.c michael@isolde:~/junk$ cat junk.s .file "junk.c" .section .rodata.str1.1,"aMS",@progbits,1 .LC0: .string "Final sum: %ld\n" .text .p2align 4,,15 .globl main .type main, @function main: .LFB22: .cfi_startproc movabsq $499999999500000000, %rdx movl $.LC0, %esi movl $1, %edi xorl %eax, %eax jmp __printf_chk .cfi_endproc .LFE22: .size main, .-main .ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3" .section .note.GNU-stack,"",@progbits

编译器想通了,我的循环,它展开来计算累积和的点,只是嵌入,作为一个常数,它进行打印出来,跳过任何一种循环完全建构的。在优化的脸聪明,你真的认为你会发现任何有意义的边缘 S =秒之间区别+ A 和 S + = A ?!

更多推荐

为A + = B比在C = A + B更有效?

本文发布于:2023-11-25 22:53:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631670.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:更有效

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!