2016년 3월 26일 토요일

Turning off OpenGL debug mode in Pyglet for Brain Workshop

I recently read an article on Infoworld by Serdar Yegulalp about performance optimizations for Python. The following tip caught my eye:

Pyglet, a handy library for creating windowed graphical applications, automatically enables a debug mode, which dramatically impacts performance until it’s explicitly disabled.
I checked the Pyglet docs for proof of this and found the following:

http://pyglet.readthedocs.org/en/latest/programming_guide/options.html

options = {'xsync': True, 'debug_gl_trace': False, 'debug_media': False, 'debug_gl': True, 'debug_font': False, 'font': ('gdiplus', 'win32'), 'audio': ('directsound', 'pulse', 'openal', 'silent'), 'debug_win32': False, 'xlib_fullscreen_override_redirect': False, 'debug_trace_depth': 1, 'debug_lib': False, 'debug_x11': False, 'debug_trace_args': False, 'debug_gl_trace_args': False, 'shadow_window': True, 'debug_texture': False, 'debug_trace_flush': True, 'darwin_cocoa': False, 'vsync': None, 'search_local_libs': True, 'debug_trace': False, 'debug_graphics_batch': False, 'graphics_vbo': True}

Apparently OpenGL debugging is turned on by default!

From the docs:
Global dict of pyglet options. To change an option from its default, you must import pyglet before any sub-packages. For example:

    import pyglet
    pyglet.options['debug_gl'] = False

debug_gl
    If True, all calls to OpenGL functions are checked afterwards for errors using glGetError. This will severely impact performance, but provides useful exceptions at the point of failure. By default, this option is enabled if __debug__ is (i.e., if Python was not run with the -O option). It is disabled by default when pyglet is “frozen” within a py2exe or py2app library archive.

I therefore added the highlighted snippet at line 814 in the Brainworkshop 4.8.7 source inside of a try-except block:

try:
    # workaround for pyglet.gl.ContextException error on certain video cards.
    os.environ["PYGLET_SHADOW_WINDOW"]="0"
    import pyglet

    # disable OpenGL debugging mode which can hurt performance
    pyglet.options['debug_gl'] = False

    from pyglet.gl import *
    if NOVBO: pyglet.options['graphics_vbo'] = False
    from pyglet.window import key
except:
    quit_with_error(_('Error: unable to load pyglet.  If you already installed pyglet, please ensure ctypes is installed.  Please visit %s') % WEB_PYGLET_DOWNLOAD)


I'm not sure how to rigorously measure the changes in execution time, however. Although Brain Workshop feels faster and is using less cpu according to htop, I would like to use something like the Python timeit module to measure a baseline for the original version and then time the edited code.