倒数比倒数快吗? [英] Is it faster to count down than it is to count up?

查看:37
本文介绍了倒数比倒数快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的计算机科学老师曾经说过,出于某种原因,倒数比倒数更有效率.例如,如果您需要使用 FOR 循环并且在某处未使用循环索引(例如将一行 N * 打印到屏幕上)我的意思是这样的代码:

Our computer science teacher once said that for some reason it is more efficient to count down than to count up. For example if you need to use a FOR loop and the loop index is not used somewhere (like printing a line of N * to the screen) I mean that code like this:

for (i = N; i >= 0; i--)  
  putchar('*');  

优于:

for (i = 0; i < N; i++)  
  putchar('*');  

是真的吗?如果是这样,有人知道为什么吗?

Is it really true? And if so, does anyone know why?

推荐答案

是真的吗?如果是这样,有人知道为什么吗?

Is it really true? and if so does anyone know why?

在古代,当计算机仍然是手工切割熔融石英时,当 8 位微控制器在地球上漫游时,当你的老师年轻(或你老师的老师年轻)时,有一种常见的机器指令叫做如果为零则递减并跳过 (DSZ).Hotshot 汇编程序员使用此指令来实现循环.后来的机器得到了更高级的指令,但仍然有相当多的处理器在这些处理器上与零比较比与其他任何比较便宜.(即使在一些现代 RISC 机器上也是如此,例如 PPC 或 SPARC,它们将整个寄存器保留为始终为零.)

In ancient days, when computers were still chipped out of fused silica by hand, when 8-bit microcontrollers roamed the Earth, and when your teacher was young (or your teacher's teacher was young), there was a common machine instruction called decrement and skip if zero (DSZ). Hotshot assembly programmers used this instruction to implement loops. Later machines got fancier instructions, but there were still quite a few processors on which it was cheaper to compare something with zero than to compare with anything else. (It's true even on some modern RISC machines, like PPC or SPARC, which reserve a whole register to be always zero.)

因此,如果您将循环与零而不是 N 进行比较,会发生什么?

So, if you rig your loops to compare with zero instead of N, what might happen?

  • 您可以保存一个寄存器
  • 您可能会得到一个二进制编码较小的比较指令
  • 如果前一条指令碰巧设置了一个标志(可能仅在 x86 系列机器上),您甚至可能不需要显式比较指令

这些差异是否可能导致对现代乱序处理器上的真实程序产生任何可衡量的改进?不大可能.事实上,如果你能在微基准测试中表现出可衡量的改进,我会印象深刻.

Are these differences likely to result in any measurable improvement on real programs on a modern out-of-order processor? Highly unlikely. In fact, I'd be impressed if you could show a measurable improvement even on a microbenchmark.

总结:我把你的老师打倒了!你不应该学习关于如何组织循环的过时的伪事实.您应该了解到关于循环的最重要的事情是确保它们终止,产生正确答案,并且易于阅读em>.我希望你的老师专注于重要的东西而不是神话.

Summary: I smack your teacher upside the head! You shouldn't be learning obsolete pseudo-facts about how to organize loops. You should be learning that the most important thing about loops is to be sure that they terminate, produce correct answers, and are easy to read. I wish your teacher would focus on the important stuff and not mythology.

这篇关于倒数比倒数快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆