关于检查和求和的愚蠢的事情 - Python
执行 if(x==num): 检查或求和 x+y 哪个更消耗 CPU 资源?
Which is more CPU intensive, to do an if(x==num): check, or to do a sum x+y?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题有些不完整,因为您正在比较两种不同的操作。如果您需要将两个东西添加在一起,那么测试
x==y
不会给您带来任何帮助。因此,想必您想与
Python 之类的解释语言进行比较,它要复杂得多,但在硬件上,非零测试会引入一个分支,而这本身可能会很昂贵。但我不想说在没有计时的情况下哪个会更快。
将不同架构的不同性能特征放入等式中,就会出现另一个混杂因素。
与往常一样,您最好首先以最自然、可维护的方式编写代码,然后再计时。如果您觉得需要获得更多性能,请使用分析器来查找热点,然后进行优化。
Your question is somewhat incomplete because you are comparing two different operations. If you need to add two things together then testing
x==y
isn't going to get you anywhere. So presumably you want to comparewith
It's a lot more complex for interpreted languages like Python, but on the hardware a test for non-zero introduces a branch and that in itself can be expensive. But I wouldn't want to say which would be faster without timing.
Throw into the equation different performance characteristics of different architectures and you have another confounding factor.
As always, you are best to write your code in the most natural maintainable way first and then time it. If you feel you need to extract more performance use a profiler to find hot spots and then optimise.