Concerns about performance w/Python, Pysco on Pentiums
John Machin
sjmachin at lexicon.net
Fri Mar 7 10:57:11 EST 2003
Pedro Rodriguez <pedro_rodriguez at club-internet.fr> wrote in message news:<b49iot$r78$1 at s1.read.news.oleane.net>...
> 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,
> 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.
Rule 1: optimize for frequent events, not for infrequent events. In
emulating a CPU, which is more frequent, valid opcode or invalid
opcode? In your get-versus-try example, you do "valid" 256 times and
"invalid" (1000000 - 256) times.
Below is a slightly more realistic test, which seems to indicate that
the try-except caper is about 50% faster than dict.get() if you never
hit the "except" clause.
Cheers,
John
8<------
import time
def getter(q):
l = {}
for i in range(256):
l[i] = i
t0 = time.time()
npass = nfail = 0
lget = l.get
for i in xrange(1000000):
x = lget(q)
if x is None:
nfail += 1
else:
npass += 1
t1 = time.time()
print "get", q, t1 - t0, npass, nfail
def tryer(q):
l = {}
for i in range(256):
l[i] = i
t0 = time.time()
npass = nfail = 0
for i in xrange(1000000):
try:
x = l[q]
except KeyError:
nfail += 1
else:
npass += 1
t1 = time.time()
print "try", q, t1 - t0, npass, nfail
for q in (0, 1, 255, -1, 256, 257):
getter(q)
tryer(q)
8<-------
=== output (Python 2.2 Windows 32 bit version, on a 1.4Ghz Athlon)
get 0 1.30199992657 1000000 0
try 0 0.871000051498 1000000 0
get 1 1.27199995518 1000000 0
try 1 0.881000041962 1000000 0
get 255 1.36199998856 1000000 0
try 255 0.950999975204 1000000 0
get -1 1.31200003624 0 1000000
try -1 7.77199995518 0 1000000
get 256 1.32100009918 0 1000000
try 256 7.77199995518 0 1000000
get 257 1.30200004578 0 1000000
try 257 7.79100000858 0 1000000
More information about the Python-list
mailing list