Reducing overhead of calling Python code by converting Python bytecode to Java bytecode #1059
Christopher-Chianelli
started this conversation in
General
Replies: 1 comment 6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
TL;DR:
Intro
Inspired by optapy/optapy#2 (comment), I decided to investigate the potential speed improvements that can be obtained by converting the Python bytecode to Java bytecode. OptaPlanner (the Java library OptaPy uses) run small functions (typically attribute getters) many times to calculate score. As such, the overhead cost typically dominates, resulting in score calculation speed at least 20 times slower than Java. I managed to translate most of Python 3.9 bytecode. The result: when translating only Joiners (and still going back to Python to set the attributes and for a filter), 500% improvement in execution time. For instance, for school timetabling:
How it works
It uses the Python's dis module to disassemble the bytecode of a Python Function. That bytecode is then passed to Java, which is translated to equivalent Java bytecode using ASM. In order to maintain 1-to-1 compatibility, a lot of operations were implemented inefficiently (for instance, integers are stored as
PythonInteger
, which wraps aBigInteger
, and define the method Python uses to perform operations).Possibilities
Unlike Jython, the translator is designed to work with CPython, and thus can be used with JPype. One possibility is to use it with
@JImplements
, specified as an additional parameter "translate_to_java_bytecode".Risks
Unlike Java, most of Python Standard Library is not available as bytecode. As a result, replacements would need to be provided for most of the standard library. Additionally, Python bytecode is not particularly stable. For instance:
Try it out
You can find the source of the translator on my python-to-java-translator branch, which also contains the relevant instructions for building and running it.
Beta Was this translation helpful? Give feedback.
All reactions