一个简单的循环中有多少个基本操作? [英] How many primitive operations in a simple loop?

查看:73
本文介绍了一个简单的循环中有多少个基本操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆代码来查找原始操作.问题在于,网络上实际上没有太多关于该主题的详细资源.在此循环中:

I have a bunch of code to find the primitive operations for. The thing is that there aren't really many detailed resources out on the web on the subject. In this loop:

for i:=0 to n do
  print test
end

我们实际上要执行几步?在我的第一个猜测中,我会说n + 1,其中n表示时间循环,n表示打印时间.然后我想也许我不够精确.甚至在每个循环中都没有向i加1的操作吗? 在这种情况下,我们有n + n + 1 = 2n + 1.正确吗?

How many steps do we really have? In my first guess I would say n+1 considering n for the times looping and 1 for the print. Then I thought that maybe I am not precise enough. Isn't there an operation even to add 1 to i in every loop? In that matter we have n+n+1=2n+1. Is that correct?

推荐答案

可以通过将循环重新铸造为while来将其分解为原始操作":

The loop can be broken down into its "primitive operations" by re-casting it as a while:

int i = 0;
while (i < n)
{
    print test;
    i = i + 1;
}

或者,更明确地说:

loop:
    if (i < n) goto done
    print test
    i = i + 1
    goto loop
done:

然后您可以看到,对于每个迭代,都有一个比较,一个增量和一个goto.那只是循环开销.您必须添加到该循环中完成的所有工作.如果print被认为是原始操作",那么您将:

You can then see that for each iteration, there is a comparison, an increment, and a goto. That's just the loop overhead. You'd have to add to that whatever work is done in the loop. If the print is considered a "primitive operation," then you have:

  • n + 1个比较
  • n个呼叫print
  • n个增量
  • n + 1个goto指令(完成后跳转到循环之外的一个指令)
  • n+1 comparisons
  • n calls to print
  • n increments
  • n+1 goto instructions (one to branch out of the loop when done)

现在,如何将所有这些转换为机器代码高度依赖于编译器,运行时库,操作系统和目标硬件.也许还有其他事情.

Now, how that all gets converted to machine code is highly dependent on the compiler, the runtime library, the operating system, and the target hardware. And perhaps other things.

这篇关于一个简单的循环中有多少个基本操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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