1

I have got to a point in my code where I need to do this:

while True:
  if first_number == second_number:
    do_something()
    break

The first number will keep incrementing beyond my control and I need to wait until this number reaches the value of the second number before I can continue.

I am looking for the best way to do this that will use up the least amount of resources (CPU).

A_Porcupine
  • 1,008
  • 2
  • 13
  • 23

3 Answers3

4

What you are doing is called "busy waiting". In order to do this without eating up CPU time, you should sleep for a short interval in each iteration of the loop:

while True:
  if first_number == second_number:
    do_something()
    break
  time.sleep(0.1)

Adjust the sleep interval as appropriate.

But there's likely a better way to accomplish what you want. How is first_number changing value if it's "out of your control"? Is your program receiving input? Reading from a socket? Are you sending a network request for data? Is this data shared among processes using multiprocessing's facilities?

Alp
  • 2,766
  • 18
  • 13
  • This is one of the solutions that I've looked at but wanted to see if there were any others. – A_Porcupine Mar 02 '14 at 16:58
  • The actual problem I'm trying to solve currently is: first_number is current time position through a song and second_number is the total duration of the song. I need to run some code when the song finishes but the built-in function to deal with this doesn't seem to be working (another question) and I was wondering about this anyway. – A_Porcupine Mar 02 '14 at 17:01
  • 1
    Still hard to recommend alternatives without knowing more about the use case (is the song playing in a subprocess? in a separate thread via some library function?). In any case, use of `sleep` for this purpose is entirely standard. – Alp Mar 02 '14 at 17:08
  • Is there any way you can make the thing asynchronous? Might take the load of needing the loop in your user code. – Will Mar 02 '14 at 17:12
0

Simply check if first number is not equal to the second number, in the while loop's condition itself.

while first_number != second_number:
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

You can try:

while first_number != second_number:
    #Do what you want
Ruben Bermudez
  • 2,293
  • 14
  • 22