romilly/quick2wire-python-api

GPIO slower on Python3 than Python2

npryce opened this issue · 1 comments

See issue #18.

Running in python 2.7 is faster than python 3.2.

!/usr/bin/env python --> 0.1 ms per GPIO change

!/usr/bin/env python3 --> 0.45 ms per GPIO change

I suspect that maybe there's some unnecessary unicode to binary conversion being performed in Python3

A bit of benchmarking seems to show that raw I/O in Python3.2 is about half the speed as in Python2.7 for the kinds of writes we're doing in the GPIO library.

The following timings were done on the 3.6.11 kernel.

nat@raspberrypi $ python3.2 -m timeit -s 'out=open("/dev/null", "w"); s="1\n"' "out.write(s)"
100000 loops, best of 3: 11.7 usec per loop
nat@raspberrypi $ python2.7 -m timeit -s 'out=open("/dev/null", "w"); s="1\n"' "out.write(s)"
100000 loops, best of 3: 5.9 usec per loop

Oddly, opening in binary mode and writing bytes is slower than writing text:

nat@raspberrypi $ python2.7 -m timeit -r 10 -s 'out=open("/dev/null", "wb"); bs=b"1\n"' "out.write(bs)"
100000 loops, best of 10: 12.5 usec per loop
nat@raspberrypi $ python3.2 -m timeit -r 10 -s 'out=open("/dev/null", "wb"); bs=b"1\n"' "out.write(bs)"
100000 loops, best of 10: 15 usec per loop

Converting from numeric or boolean to text is also a bit slower in Python3.2.

nat@raspberrypi $ python2.7 -m timeit "str(1)"
100000 loops, best of 3: 4.45 usec per loop
nat@raspberrypi $ python3.2 -m timeit "str(1)"
100000 loops, best of 3: 5.52 usec per loop

nat@raspberrypi $ python3.2 -m timeit -r 10 "str(True)"
100000 loops, best of 10: 5.34 usec per loop
nat@raspberrypi $ python2.7 -m timeit -r 10 "str(True)"
100000 loops, best of 10: 4.64 usec per loop