mercredi 28 juin 2017

Reduce CPU time of if-elif statements

I have an if-elif statement, which I believe not be very efficient:

number = 1000

switch = {
    '1': False,
    '2': False,
    '3': False,
    '4': False,
    '5': False,
    '6': False,
    '7': False,
    '8': False,
    '9': False
}

for i in range(number):
    for j in range(number):
        if some_condition:
            if i <= something and j <= something:
                switch['1'] = True
            elif i <= something and j <= something:
                switch['2'] = True
            elif something < i <= something and j <= something:
                switch['3'] = True
            elif something <= i < something and j < something:
                switch['4'] = True
            elif something <= i < something and something < j something:
                switch['5'] = True
            elif something <= i < something and something and j >= something:
                switch['6'] = True
            elif i >= something and j <= something:
                switch['7'] = True
            elif i >= something and something < j <= something:
                switch['8'] = True
            elif i >= something and  j >= something:
                switch['9'] = True

for i in switch:
    if(switch[i] == True):
        print(i)

As you can see, the statement looks pretty ugly. Since number is big, it takes almost 2 seconds for the execution.

Is there any way I could lower the CPU time?

I tried this answer, but my statement conditions are different.

Thank you.

Aucun commentaire:

Enregistrer un commentaire