I'm a beginner and made this python script so that my computer will play "azan" during prayer times automatically. I realized that when my program is running, it uses 29.1% of my CPU. I suspect this is coming from:
while True:
global azan_subuh, norm_azan
# retrieving current time
current_time = datetime.now().strftime("%I:%M %p")
# playing azan subuh
if current_time == prayer_times[0]:
mixer.music.load(azan_subuh)
mixer.music.play()
time.sleep(3600)
# playing normal azan
elif current_time in prayer_times[2:6]:
mixer.music.load(norm_azan)
mixer.music.play()
time.sleep(3600)
when both conditions are False. time.sleep(3600)
is added because prayer times are at least one hour apart. I also realized when time.sleep(3600)
is running, the program only uses 0.3% of CPU which narrowed down the suspect that hogs CPU usage to the while loop above.
How do I optimize my program further so that it won't use CPU that much?
Here is the whole script. If there are any suggestions on improving the program in other parts of the code, please feel free and comment down as it would help me a lot.
from datetime import datetime # for time functionality
from bs4 import BeautifulSoup # for web-parsing functionality
from pygame import mixer # for mp3 compatibility
import requests
import time
# for saving all prayer times on that particular day
prayer_times = list()
# defining and initializing global vars for azan locations
azan_subuh = "c:/Users/AmmarFMR/Music/Azan/azan_subuh.mp3"
norm_azan = "c:/Users/AmmarFMR/Music/Azan/norm_azan.mp3"
def parser():
# getting html file from website & parsing it
source = requests.get("https://www.islamicfinder.org/world/malaysia/1735150/rawang-prayer-times/").text
html = BeautifulSoup(source, "lxml")
global prayer_times
# getting the prayer times
prayer_times = html.find_all("div", class_="todayPrayerDetailContainer")
# cleaning up prayer_times list
for n in range(len(prayer_times)):
prayer_times[n] = prayer_times[n].text.split("\n")[1]
def main():
global prayer_times
while True:
global azan_subuh, norm_azan
# retrieving current time
current_time = datetime.now().strftime("%I:%M %p")
# playing azan subuh
if current_time == prayer_times[0]:
mixer.music.load(azan_subuh)
mixer.music.play()
time.sleep(3600)
# playing normal azan
elif current_time in prayer_times[2:6]:
mixer.music.load(norm_azan)
mixer.music.play()
time.sleep(3600)
# for the execution of the program
if __name__ == "__main__":
mixer.init()
parser()
main()
else:
print("This program is not meant to be used by other scripts.")
time.sleep(3)
exit(2)