I need to know if there is any way I can optimize my code so that it does not use 0.6% of my total memory - which is approx. 22.4MB. This is a really small script that runs for as long as the raspberry pi is ON. 22.4MB for this basic, simple, light code is too much. If less or no optimization is there, then please let me know how 22.4MB is justified.

I am pasting the htop screenshot and my full script.


from gpiozero import CPUTemperature
from time import sleep, time
from requests import post

class TemperatureBot:
    def __init__(self):
        self.lastAlertSent = -1
        self.chatId = "123"
        self.botToken= "123"
        self.temperatureThreshold = 60
        self.alertInterval = 300
        alertResp = self.sendAlertToUser(f"Initializing temperature bot for 123 - " \
                                         f"your pi")
        if alertResp is not True:
            print("Could not initialize bot for 123. Try later.")

    def sendAlertToUser(self, alertMsg):
            r = post(url,timeout=20)
            if(r.status_code >=400):
                print("Error sending alert. Here's the response: ", r.text)
                return False
            return True
        except Exception as e:
            raise e

    def temperaturePolling(self):
                currentTemp = CPUTemperature().temperature
                if(currentTemp > self.temperatureThreshold):
                    if(time() - self.lastAlertSent > self.alertInterval):
                        alertResp = self.sendAlertToUser(f"Temperature Danger: "\
                                             f"{currentTemp}°C. "\
                                             f"Please cool your Stan "\
                                             f"or it will burn!!")
                        if alertResp == True:
                            self.lastAlertSent = time()
                            print("Could not send alert message.")
        except KeyboardInterrupt:

if __name__ == "__main__":

  • 2
    \$\begingroup\$ I don't think it'll get much lower - at least on my system, python -c 'import requests, time; time.sleep(600)' & uses similar amounts of memory even though all it does is import requests and go to sleep \$\endgroup\$
    – Sara J
    Commented Jun 25, 2021 at 23:51
  • \$\begingroup\$ @SaraJ I thought there was something wrong in my code login which is taking too much memory but it's them libraries! Thanks for demonstration! \$\endgroup\$ Commented Jun 29, 2021 at 20:38

1 Answer 1

  • chatId -> chat_id and similar for other members and method names, by PEP8 standard
  • f"Initializing temperature bot for 123 - " does not need to be an f-string - it has no fields
  • if alertResp is not true, you should be raising an exception, not early-returning
  • if alertResp is not True is equivalent to if not alertResp
  • temperaturePolling should not be called from your constructor - the constructor is only for initialization
  • post returns a response that should be used in a with context manager
  • status_code >= 400 can safely be replaced with r.ok, or better yet r.raise_for_status()
  • except Exception as e: raise e should be deleted entirely
  • except KeyboardInterrupt: pass is fine if it's done at the upper level, but not in your polling routine
  • \$\begingroup\$ > "except Exception as e: raise e should be deleted entirely" . But we have to catch after a try block, so how do we do that if we remove the block entirely? \$\endgroup\$ Commented Jun 26, 2021 at 19:33
  • 1
    \$\begingroup\$ Remove the try as well. It's not helping you \$\endgroup\$
    – Reinderien
    Commented Jun 26, 2021 at 19:34
  • \$\begingroup\$ Thanks @Reinderien, have made the changes and made a note of the same for future. BTW, when I'm calling this polling routine at the upper level(say pollingCaller), the code gets stuck in the while loop of this polling routine and the code following the pollingCaller doesn't get executed. In your experience do you have any solutions to that? Or should I ask that as a separate question on stackexchange? \$\endgroup\$ Commented Jun 26, 2021 at 19:42
  • \$\begingroup\$ Under what conditions does the polling loop end? What kind of code would execute after? \$\endgroup\$
    – Reinderien
    Commented Jun 26, 2021 at 19:43
  • \$\begingroup\$ This script I am planning to run it as a cron job on system reboot. @reboot thingy. So I don't think that the polling loop ever ends (as long as the system is ON). The code that is followed by the polling calling is telegram bot codes, basically some listeners, callbacks. Please have a glimpse here: pastebin.com/5y6Rs8xe \$\endgroup\$ Commented Jun 26, 2021 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.