Every once in a while, Python is too slow

I recently acquired a USB-connected relay that controls a standard power outlet, called the "USB NET POWER 8800". I'd ordered this with the knowledge that there was a Python implementation of the control program that was said to run on Linux.

It does work, but I was stunned at how long it took to switch the outlet on or off: a couple of seconds! I should disclaim that it's running on a rather underpowered machine (the OLPC XO-1 with a Geode x86 CPU @ 430MHz), but this was way too long to be acceptable:

$ time py-usbpower query
Power: on

real    0m2.690s
user    0m1.484s
sys     0m0.096s
With some detective work, I discovered that ctypes is doing things like running the compiler, objdump(!) and ldconfig(!), several times (!!), at each invocation of the program. (this is python2.5, but it looks like Python 2.7's ctypes still does essentially the same thing, unfortunately)

I set about to code this in C. For my reward, I got a very fast-executing program:

$ time c-usbpower status
ON

real    0m0.007s
user    0m0.000s
sys     0m0.000s

That's something like a 384x speedup. Lesson? ctypes has some very substantial startup costs for loading a library. It may be enough to make it unsuitable for a short-lived program.

In case it's useful to you, I enclose a copy of my usbpower program. It's under the terms of the GNU GPLv2.

Files currently attached to this page:

usbpower.c3.4kB



Entry first conceived on 28 February 2012, 3:19 UTC, last modified on 6 March 2012, 1:38 UTC
Website Copyright © 2004-2024 Jeff Epler