How many primitive operations in a simple loop?

喜夏-厌秋 提交于 2019-12-03 23:19:58

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.

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