Optimizie OpCode loading
authorIustin Pop <iustin@google.com>
Fri, 17 Jul 2009 12:54:30 +0000 (14:54 +0200)
committerIustin Pop <iustin@google.com>
Fri, 17 Jul 2009 13:30:00 +0000 (15:30 +0200)
This patch converts the opcode loading to a pre-built map (at import
time) instead of iteration over the globals dict at each call.

Microbenchmarks show that this should be around three times faster, and
burnin still passes.

Signed-off-by: Iustin Pop <iustin@google.com>
Reviewed-by: Michael Hanselmann <hansmi@google.com>

lib/opcodes.py

index 535db91..6ba30f6 100644 (file)
@@ -142,14 +142,9 @@ class OpCode(BaseOpCode):
       raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
     op_id = data["OP_ID"]
     op_class = None
-    for item in globals().values():
-      if (isinstance(item, type) and
-          issubclass(item, cls) and
-          hasattr(item, "OP_ID") and
-          getattr(item, "OP_ID") == op_id):
-        op_class = item
-        break
-    if op_class is None:
+    if op_id in OP_MAPPING:
+      op_class = OP_MAPPING[op_id]
+    else:
       raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
                        op_id)
     op = op_class()
@@ -578,3 +573,7 @@ class OpTestAllocator(OpCode):
     "mem_size", "disks", "disk_template",
     "os", "tags", "nics", "vcpus", "hypervisor",
     ]
+
+OP_MAPPING = dict([(v.OP_ID, v) for v in globals().values()
+                   if (isinstance(v, type) and issubclass(v, OpCode) and
+                       hasattr(v, "OP_ID"))])