-->
Page 1 of 1

Bit-Banging, Performance, and Lua Table Lookups

PostPosted: Fri Dec 12, 2014 3:52 pm
by Markus Gritsch
Hi,

just in case someone is interrested, I'd like to share my findings on improving the performance on pin toggling used e.g. when bit-banging some data:

timings.png

The screen shot above shows some measurements I made with my Logic Pirate. The corresponding Lua code is shown below:

Code: Select allpin = 9 -- 8 .. GPIO 0, 9 .. GPIO 2
gpio.mode(pin, gpio.OUTPUT)

-- 1
for i = 1, 2 do
  gpio.write(pin, gpio.HIGH)
  gpio.write(pin, gpio.LOW)
end

-- 2
for i = 1, 2 do
  gpio.write(pin, 1)
  gpio.write(pin, 0)
end

-- 3
gpio_write = gpio.write
for i = 1, 2 do
  gpio_write(pin, 1)
  gpio_write(pin, 0)
end

-- 4
for i = 1, 2 do
  gpio_write(9, 1)
  gpio_write(9, 0)
end

As one would expect, table lookups make things quite slow. The 1st loop has two lookups per pin state change, taking about 100 us. In the 2nd loop, when eliminating the lookup for gpio.HIGH and gpio.LOW and using 1 and 0 instead, the speed roughly doubles to 50 us. The 3rd loop uses a variable instead of the table lookup for gpio.write which leads to about 11 us, and in the 4th loop the variable lookup for pin is also eliminated shaving off another us.

So from 100 us to 10 us is quite some improvement, I would say :)

Cheers and have fun,
Markus

Re: Bit-Banging, Performance, and Lua Table Lookups

PostPosted: Fri Dec 12, 2014 4:25 pm
by hwiguna
Wow! That's a cool trick! Thanks for sharing Markus!

Re: Bit-Banging, Performance, and Lua Table Lookups

PostPosted: Fri Dec 12, 2014 5:45 pm
by gerardwr
Yes, that's an excellent test. I was wondering what performance the ESP would have in bit banging.

100 usec is nice for the interpreter, but 10us is much better!

Well done, thanks for sharing.