How many primitive operations in a simple loop?

自作多情 提交于 2019-12-05 07:50:54

问题


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

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?


回答1:


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;
}

Or, more explicitly:

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

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 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.



来源:https://stackoverflow.com/questions/5069840/how-many-primitive-operations-in-a-simple-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!