vshymanskyy / blynk-library-python

Blynk library for Python. Works with Python 2, Python 3, MicroPython.
https://blynk.io/
MIT License
281 stars 97 forks source link

Every python program takes 100% CPU on my raspi #6

Closed optiprime closed 5 years ago

optiprime commented 7 years ago

In contrast to the C version which only takes about 1% CPU, the python version saturates a full CPU core all the time even for the smallest setups (only one virtual port with polling interval of 30 s).

IndyJoeA commented 7 years ago

I noticed that too, so I put in a 0.5 second sleep in the sleep_from_until() function, and that has reduced CPU usage dramatically without affecting responsiveness, but it's probably no longer in spec with the protocol.

optiprime commented 7 years ago

Thanks for your hint. It worked for me, too. As I observed a slightly reduction in responsiveness, I reduced the sleep time to 0.01 (1/100) seconds. With this setting, the CPU load of the program is about 1 - 2 % and the application is as responsive as without any sleeps.

IndyJoeA commented 7 years ago

Glad that helped! The one problem I'm noticing after doing that is that every so often the Blynk server connection will be lost and the library will not reconnect, so I've modified the library so that I can run it in a separate thread and restart it when it disconnects.

malvar0929 commented 6 years ago

I'm also having high CPU load on one core. Could someone please tell me how I can implement this fix to the Blynk python library. Thank you in advance.

optiprime commented 6 years ago

follow the commit of clvz (see above) or just insert the line time.sleep(0.01) into the method sleep_from_until.

malvar0929 commented 6 years ago

Not sure what I'm doing wrong but even after trying time.sleep(0.01) or (.5) and even followed clvz's commit and I still get same result, 1 core @100%. Can someone please see code snippet below and tell if I'm doing something wrong. Thank you for the help.

def sleep_from_until (start, delay): while time.ticks_diff(start, time.ticks_ms()) < delay: idle_func() return start + delay time.sleep(0.5) class VrPin: def init(self, read=None, write=None): self.read = read self.write = write

optiprime commented 6 years ago

That was the wrong place. Please move it right before the "return start + delay" line and make sure it has the same indentation as this line.

malvar0929 commented 6 years ago

It works now! Thank you optiprime, I can finally start using this library now without having to worry about 1 core always on max, and for my project it means I'll save a little bit of battery life too.

vshymanskyy commented 5 years ago

Validated on 0.2.0 (current master, to be released soon)

vshymanskyy commented 5 years ago

v0.2.0 is released and available via pip: https://github.com/vshymanskyy/blynk-library-python/releases/latest