如何优化此代码以减少CPU消耗

2024-04-27 00:14:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python代码,它有一个无限循环,可以精确地扫描raspberry pi的pin。但是对于pi来说,它是非常消耗资源的。请有人建议我如何在代码中减少CPU的使用。你知道吗

from matrixKeypad_RPi_GPIO import keypad
from time import sleep
import urllib2
kp = keypad()
var = 1
s1=True
s2=True
s3=True
s4=True
s5=True
s6=True
s7=True
def digit():
    # Loop while waiting for a keypress
    r = None
    while r == None:
        r = kp.getKey()
    return r
while var == 1:
    d=digit()
    if d==1:
        if s1==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r1=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r1=OFF')
        s1^=True
    if d==2:
        if s2==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r2=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r2=OFF')
        s2^=True
    if d==3:
        if s3==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r3=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r3=OFF')
        s3^=True
    if d==4:
        if s4==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r4=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r4=OFF')
        s4^=True
    if d==5:
        if s5==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r5=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r5=OFF')
        s5^=True
    if d==6:
        if s6==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r6=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r6=OFF')
        s6^=True
    if d==7:
        if s7==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r7=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r7=OFF')
        s7^=True
    sleep(1)

Tags: importcmdtruehttpifs3onurllib2