4

I am trying to figure out how a while loop determines how much memory to use.

At the basic level:

while True:
    pass

If I did a similar thing in PHP, it would grind my localhost to a crawl. But in this case I would expect it to use next to nothing.

So for an infinite loop in python, should I expect that it would use up tons of memory, or does it scale according to what is being done, and where?

1Up
  • 994
  • 2
  • 12
  • 24

1 Answers1

6

Your infinite loop is a no-op (it doesn't do anything), so it won't increase the memory use beyond what is being used by the rest of your program. To answer your question, you need to post the code that you suspect is causing memory problems.

In PHP however, the same loop will "hang" because the web server is expecting a response to send back to the client. Since no response is being received, the web browser will simply "freeze". Depending on how the web server is configured, it may choose to end the process an issue a timeout error.

You could do the same if you used Python and a web framework and put an infinite loop in one of your methods that returns a response to the client.

If you ran the equivalent PHP code from the shell, it will have the same effect as if it was written in Python (or any other language). That is, your console will block until you kill the process.


I'm asking because I want to create a program that runs infinitely, but I'm not sure how to determine it's footprint or how much it will take from system resources.

A program that runs indefinitely (I think that's what you mean) - it generally has two cases:

  1. Its waiting to do some work on a trigger (like a web server runs indefinitely, but its just sitting there until someone visits your website)

  2. Its doing a process that is taking a long time.

For #2, you need to determine the resource use by figuring out what is the work being done.

If its building a large list of items to do some calculations/sorting, then memory use will grow as the list grows.

If its processing a bunch of files, and during this process, it generates a lot of output stored on disk - then disk usage will grow, and then shrink when the process is done.

If its a rendering engine, then memory use and CPU use will increase, along with disk use as the memory is swapped out during rendering. However, such a system will not tax the disk too much.

The bottom line is, you can't get an answer to this unless you explain the process being run.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • Thats wonderful. I'm asking because I want to create a program that runs infinitely, but I'm not sure how to determine it's footprint or how much it will take from system resources. – 1Up Aug 07 '14 at 04:20
  • I don't want to break the Stackoverflow rule of conversations, but I'm playing around with a twitter streamer that does a few interactions. Ultimately it would just run all day. Perhaps I'm completely wrong in my approach? – 1Up Aug 07 '14 at 04:26