Writing an emulator in python - implementation questions (for performance)

Baptiste Lepilleur baptiste.lepilleur at gmail.com
Sun Nov 15 17:12:53 EST 2009


I think you can use python itself for "pre-processing". Here is an
(shortened) example from PyPy RPython paper:

# operators: the docstrings contain the
# symbol associated with each operator
class Op_Add(BinaryExpr):
    ’+’
class Op_Sub(BinaryExpr):
    ’-’

# INIT-TIME only: build the table of
# opcodes and add the ’eval’ methods
def gen_eval(ch):
    code = """
    def eval(self):
        return self.l.eval() %s self.r.eval()
    """
    d = {}
    exec code.strip() % (ch) in d
    return d['eval']
OPCODES = {}
def build_opcodes():
    for name, value in globals().items():
        if name.startswith(’Op_’):
            value.eval = gen_eval(value.__doc__)
            OPCODES[value.__doc__] = value
build_opcodes()

>From the paper:
"""
The eval method is generated via a call to the helper
routine gen_eval, which creates a string of Python code that
performs the desired computation and uses exec to compile
this string into a Python method.

Adding the class object to the OPCODES dictionary is done
by simple assignment, using the class docstring as the key
and the class object itself as the value.
"""

You might also want to have a look at PyGirl, the Nintendo Gameboy emulator
of the PyPy project written in RPython (a subset of Python that allow static
type inference). There is probably some ideas to borrow. The paper on PyGirl
also details some of the "pre-processing" trick they used. They sometime
call it meta-programming but its all the same, generating code with code :).

See http://codespeak.net/pypy/dist/pypy/doc/extradoc.html for more info and
look-up the rpython and pygirl docs.

2009/11/14 greg <greg at cosc.canterbury.ac.nz>

> Santiago Romero wrote:
>
>   Can the above be easily done with another already-existing
>> application? (example: can m4 do this job)?
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091115/ef2b6a70/attachment-0001.html>


More information about the Python-list mailing list