如何优化此程序以降低CPU使用率?

时间:2017-12-28 09:57:26

标签: python python-3.x python-3.6

我是初学者并制作了这个python脚本,以便我的电脑可以播放" azan"在祈祷时间自动。我意识到当我的程序运行时,它占用了我CPU的29.1%。我怀疑这是来自:

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)

当两个条件都为假时。添加time.sleep(3600)因为祷告时间至少相隔一小时。我还意识到当time.sleep(3600)正在运行时,程序只使用0.3%的CPU,从而缩小了将CPU使用率提高到上面的while循环的嫌疑人。

如何进一步优化我的程序,以便它不会那么多地使用CPU?

这是整个脚本。如果在代码的其他部分有任何改进程序的建议,请随意和评论,因为它会对我有所帮助。

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)

1 个答案:

答案 0 :(得分:1)

你的脚本占用CPU时间,因为大多数时候它不断检查它是否是特殊时期之一;检查之间没有延迟,因此它被称为“忙碌循环”#34;主循环中不到一秒钟的简单睡眠应该可以解决这个问题,所以它每秒只检查几次,而不是每次检查完毕:

while True:

    time.sleep(0.1)  # Avoid unnecessary checking

    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)