Ich empfange Punkte in großer Anzahl von einem Sensor in Echtzeit. Ich benötige jedoch nur vier Kategorien von Punkten, nämlich top_left, top_right, bottom_left und bottom_right. Ich habe eine if-Anweisung in elif Python 2 wie folgt:Schneller als if-elif-Anweisung
from random import random, randint
# points below are received from sensor. however,
# here in this post I am creating it randomly.
points = [Point(randint(0, i), random(), random(), random()) for i in range(100)]
# 4 categories
top_left, top_right, bottom_left, bottom_right = None, None, None, None
for p in points:
if p.id == 5:
top_left = p
elif p.id == 7:
top_right = p
elif p.id == 13:
bottom_left = p
elif p.id == 15:
bottom_right = p
print top_left.id, top_left.x, top_left.y, top_left.z # check variable
Jeder Punkt hat eine ID und x, y, z-Parameter. Dies ist eine eingebaute Klasse. Ich zeige hier nur eine Beispielklasse.
Gibt es einen effizienten Weg, um die gleiche Laufzeit zu erreichen.
Antwort: Ich füge die Ergebnisse hinzu, die ich von den Antworten erhalten habe. Es scheint, dass the answer by Elis Byberi am schnellsten ist. Unten ist mein Testcode:
class Point():
def __init__(self, id, x, y, z):
self.id = id
self.x = x
self.y = y
self.z = z
from random import random, randint
n = 1000
points = [Point(randint(0, i), random(), random(), random()) for i in range(n)]
def method1():
top_left, top_right, bottom_left, bottom_right = None, None, None, None
for p in points:
if p.id == 5:
top_left = p
elif p.id == 7:
top_right = p
elif p.id == 13:
bottom_left = p
elif p.id == 15:
bottom_right = p
#print top_left.id, top_left.x, top_left.y, top_left.z
def method2():
categories = {
5: None, # top_left
7: None, # top_right
13: None, # bottom_left
15: None # bottom_right
}
for p in points:
categories[p.id] = p
top_left = categories[5]
#print top_left.id, top_left.x, top_left.y, top_left.z
def method3():
name_to_id = {'top_left': 5, 'top_right': 7, 'bottom_left': 13, 'bottom_right': 15}
ids = [value for value in name_to_id.values()]
bbox = {id: None for id in ids}
for point in points:
try:
bbox[point.id] = Point(point.id, point.x, point.y, point.z)
except KeyError: # Not an id of interest.
pass
top_left = bbox[name_to_id['top_left']]
#print top_left.id, top_left.x, top_left.y, top_left.z
from timeit import Timer
print 'method 1:', Timer(lambda: method1()).timeit(number=n)
print 'method 2:', Timer(lambda: method2()).timeit(number=n)
print 'method 3:', Timer(lambda: method3()).timeit(number=n)
Siehe unten die zurückgegebenen Ausgabe:
[email protected]:~/Desktop$ python test.py
method 1: 0.174991846085
method 2: 0.0743980407715
method 3: 0.582262039185
In welcher Weise effizient? Laufzeit, Lesbarkeit oder Zeitaufwand für die Eingabe? –
@NickPredey: Runtime –
Das ist so effizient, wie eine Kontrollstruktur bekommen kann, denke ich – arielnmz