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.")
return
self.temperaturePolling()
def sendAlertToUser(self, alertMsg):
try:
url=f"https://api.telegram.org/bot{self.botToken}"\
f"/sendMessage?chat_id={self.chatId}&text={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):
try:
while(True):
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()
else:
print("Could not send alert message.")
continue
sleep(30)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
TemperatureBot()
python -c 'import requests, time; time.sleep(600)' &
uses similar amounts of memory even though all it does is importrequests
and go to sleep \$\endgroup\$