Python Forum
Is using while True loop good?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is using while True loop good?
#1
Hi,
I've created a process in which I've used one while True loop for watch on a changeable variable. If the variable change something happens, otherwise the while loop rotates blank. This process is intended to be used in comparatively low resource machine, like Raspberry pi 4, 2GB.
My question is, will this ever rotating while True loop makes my process resource hungry, as it rotates at it's full speed until the conditions mate?

Please see the simplified code below:

def do_something():
    <something happens>

changableVariable = <updated by other thread>
comparingVariable = None

while True:
    if changableVariable != comparingVariable:
        do_something()
        comparingVariable = changableVariable
In the above scenario until 'changableVariable' changes this while True loop [Line 7] is rotating in full speed after first run.
Please help me to understand.
I'm a noob in python as well as programming.

______
Raspberry pi OS (32bit)
python 3.7x
Reply
#2
It would constantly loop so whilst it doesn't seem like the code would use up much resource it doesn't seem sensible.
I'd at least add a time delay to loop every 5 minutes or something. time.sleep(300) will but 5 minutes between each check.

There are better ways to do this but i'm unsure as to what your overall goal is but sleep function should help.
Reply
#3
(Jul-02-2020, 04:36 PM)HarleyQuin Wrote: It would constantly loop so whilst it doesn't seem like the code would use up much resource it doesn't seem sensible.
I'd at least add a time delay to loop every 5 minutes or something. time.sleep(300) will but 5 minutes between each check.

There are better ways to do this but i'm unsure as to what your overall goal is but sleep function should help.

Thank you for replying.
I've also thought about it.
5 minutes interval will be too large for my purpose.
1-5 millisecond will do.

To check approximate full speed I've used this code:
import time


def get_second_microsecond():
    """Returns current UTC second and microsecond as list"""
    gettime = time.time()
    second = int(gettime)
    microsecond = int(round((gettime - second), 6) * 1000000)
    timelist = [second, microsecond]
    return timelist


starttime = get_second_microsecond()
changingvariable = 0
comparingvariable = 1

for i in range(1000000):
    if changingvariable != comparingvariable:
        print('changing variable= {}, comparing variable= {}'.format(changingvariable, comparingvariable))
        comparingvariable = changingvariable
        print('changing variable= {}, comparing variable= {}'.format(changingvariable, comparingvariable))

endtime = get_second_microsecond()
totaldelay = (endtime[1] - starttime[1])
print('start time= {0[0]}.{0[1]}'.format(starttime))
print('end time= {0[0]}.{0[1]}'.format(endtime))
print('Total Delay= {} microsecond'.format(totaldelay))
Output:
changing variable= 0, comparing variable= 1 changing variable= 0, comparing variable= 0 start time= 1593730068.643423 end time= 1593730068.788341 Total Delay= 144918 microsecond Process finished with exit code 0
Grossly 7 million loops per second. will it not jam a part of the CPU?

if I put a 5 ms delay for 100 loops:
Output:
changing variable= 0, comparing variable= 1 changing variable= 0, comparing variable= 0 start time= 1593731128.280446 end time= 1593731128.816871 Total Delay= 536425 microsecond
Grossly 200 loops per second.
Hmm...
OK that might be an workaround.
But I am keeping this thread as unsolved if anyone have other explanation or other workaround.
Anyway, thanks again.
Reply
#4
Sure, its also important to take into account the time it will take your function to complete.

What sort of function are you using? Does it take long to execute? The more code you add then naturally your while loop will slow down without any sleep function.

Its tough to give you advise on code because i don't know what you are trying to accomplish overall!

Wish i could offer more help,

Harley
Reply
#5
maybe you can elaborate on what you are actually doing. there might be better approach to achieve it. at the moment this looks very much like XY problem
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
(Jul-03-2020, 09:49 AM)HarleyQuin Wrote: Sure, its also important to take into account the time it will take your function to complete.

What sort of function are you using? Does it take long to execute? The more code you add then naturally your while loop will slow down without any sleep function.

Its tough to give you advise on code because i don't know what you are trying to accomplish overall!

Wish i could offer more help,

Harley

Thank you for the response.

The whole pipe is like this, there are two processes which collects data. One from serial port another from another local machine via TCP. Third process stores in db and compares data of other two processes. So, process 1 and stores collected data in two variable and the third one do have two shadow variable of process 1 and 2 which is getting continually updated via TCP. So, the TCP client should continually watch for changes on the variable for any change.
The time taken by do_something function is not of any concern, because even it do take a long time, noting changes, as it'll run only once when variable changes, whole the other time (it may be minutes or hours, until the changableVariable changes) the while loop runs free. Inside of the do_something function collects the variable changes to a custom application layer protocol data and sends via TCP. As it nothing to do with my question so, I avoided those ~150 lines of code which will only jumble up the post, and readers have to spend a lot of time to read, understand and figure out that, in the code where my question lies. So, to keep it brief and to the point I've written this stripped down code to as pin pointed to the question as I can.
So, finally once again my concern is to keep an watch on a variable, whenever it changes something happens. How to do that efficiently? As per my code above how to keep an watch on the 'changableVariable', whenever it changes do_something function runs? If you suggest any other workaround except using while True loop, you're welcome.
Hope you understand and..... Thanks again.

(Jul-03-2020, 10:11 AM)buran Wrote: maybe you can elaborate on what you are actually doing. there might be better approach to achieve it. at the moment this looks very much like XY problem

Thank you for the response.
I've explained the pipeline in previous reply. Please refer to that.
Your explanation on importing module saved my day man!
Thanks again.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  While True loop help Nickd12 2 1,957 Oct-17-2020, 08:12 AM
Last Post: Nickd12
  Do break operators turn while loop conditions from True to False? Drone4four 5 2,895 Oct-24-2019, 07:11 PM
Last Post: newbieAuggie2019
  How to use while true/while loop on python christing 4 2,833 Oct-08-2019, 08:02 AM
Last Post: perfringo
  Returning True or False vs. True or None trevorkavanaugh 6 9,112 Apr-04-2019, 08:42 AM
Last Post: DeaD_EyE
  file.write stops while true loop from executing in python3 boonr 3 3,050 Mar-25-2019, 12:50 PM
Last Post: ichabod801
  How to make loop go back to the beginning if test evaluaes to True. FWendeburg 1 2,798 Feb-13-2019, 01:26 AM
Last Post: stullis
  Returning true or false in a for loop bbop1232012 3 8,036 Nov-22-2018, 04:44 PM
Last Post: bbop1232012
  Get True of false outside a loop morgandebray 2 2,415 Aug-09-2018, 12:39 PM
Last Post: morgandebray

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020