Concerns about performance w/Python, Pysco on Pentiums

Pedro Rodriguez pedro_rodriguez at club-internet.fr
Fri Mar 7 02:48:55 EST 2003


On Thu, 06 Mar 2003 20:35:14 +0100, Peter Hansen wrote:

>     def step(self):
>         opcodeByte = self.readByte(self.PC)
>         try:
>             opcode = self.opcodes[opcodeByte]
>         except KeyError:
>             raise UnimplementedOpcode('$%02X %s' % (opcodeByte,
> self.readMemory(self.PC + 1, 5)))
>         else:
>             ...

if you are using a dictionnary for opcodes, wouldn't you gain
time by not putting a try/except clause but by going straight
with self.opcodes.get(...) and checking the returned value 
against None.

import time

l = {}
for i in range(256):
    l[i] = i

t0 = time.time()
for i in range(1000000):
    x = l.get(i)
    if x is None:
        pass
    else:
        pass
t1 = time.time()
print "get", t1 - t0

t0 = time.time()
for i in range(1000000):
    try:
       x = l[i]
    except KeyError:
        pass
    else:
        pass
t1 = time.time()
print "try", t1 - t0

$ time python t.py
get 2.30093002319
try 13.6490590572

real    0m15.995s
user    0m15.650s
sys     0m0.110s


Pedro




More information about the Python-list mailing list