What is a “tight loop”?

2019-01-11 02:23发布

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

An example would help.

标签: terminology
7条回答
forever°为你锁心
2楼-- · 2019-01-11 02:48

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.

查看更多
Deceive 欺骗
3楼-- · 2019-01-11 02:52

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) {}
查看更多
别忘想泡老子
4楼-- · 2019-01-11 02:52

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

查看更多
混吃等死
5楼-- · 2019-01-11 02:52

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

查看更多
疯言疯语
6楼-- · 2019-01-11 02:55

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.

查看更多
Anthone
7楼-- · 2019-01-11 02:55

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.

查看更多
登录 后发表回答