What is a “tight loop”?

若如初见. 提交于 2019-11-26 18:13:01

问题


I've heard that phrase a lot. What does it mean?

An example would help.


回答1:


From Wiktionary:

  1. (computing) In assembly languages, a loop which contains few instructions and iterates many times.
  2. (computing) Such a loop which heavily uses I/O or processing resources, failing to adequately share them with other programs running in the operating system.

For case 1 it is probably like

for (unsigned int i = 0; i < 0xffffffff; ++ i) {}



回答2:


I think the phrase is generally used to designate a loop which iterates many times, and which can have a serious effect on the program's performance - that is, it can use a lot of CPU cycles. Usually you would hear this phrase in a discussion of optimization.

For examples, I think of gaming, where a loop might need to process every pixel on the screen, or scientific app, where a loop is processing entries in giant arrays of data points.




回答3:


There's a good example of a tight loop (~ infinite loop) in the video Jon Skeet and Tony the Pony.

The example is:

while(text.IndexOf("  ") != -1) text = text.Replace("  ", " ");

which produces a tight loop because IndexOf ignores a Unicode zero-width character (thus finds two adjacent spaces) but Replace does not ignore them (thus not replacing any adjacent spaces).

There are already good definitions in the other answers, so I don't mention them again.




回答4:


A tight loop is one which is CPU cache-friendly. It is a loop which fits in the instruction cache, which does no branching, and which effectively hides memory fetch latency for data being processed.




回答5:


SandeepJ's answer is the correct one in the context of Network appliances (for an example, see Wikipedia entry on middlebox) that deal with packets. I would like to add that the thread/task running the tight loop tries to remain scheduled on a single CPU and not get context switched out.




回答6:


According to Webster's dictionary, "A loop of code that executes without releasing any resources to other programs or the operating system."

http://www.websters-online-dictionary.org/ti/tight+loop.html




回答7:


From experience, I've noticed that if ever you're trying to do a loop that runs indefinitely, for instance something like:

while(true)
{
    //do some processing
}

Such a loop will most likely always be resource intensive. If you check the CPU and Memory usage by the process with this loop, you will find that it will have shot up. Such is the idea some people call a "tight loop".



来源:https://stackoverflow.com/questions/2212973/what-is-a-tight-loop

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