vsergeev / lua-periphery

A Lua library for peripheral I/O (GPIO, LED, PWM, SPI, I2C, MMIO, Serial) in Linux.
MIT License
182 stars 38 forks source link

Reading GPIO is extremely slow #11

Closed gw0 closed 8 years ago

gw0 commented 8 years ago

I was benchmarking the speed of reading GPIO ports in different ways, and with lua-periphery it is extremely slow (using one open per read, because of #10).

GPIO = require("periphery").GPIO
OUTPUT = "out"
INPUT = "in"

--local gpio = GPIO(22, INPUT)  -- XXX: issue #10
c = 0
while (c < 100000) do
  --local data = gpio:read()  -- XXX: issue #10
  local data = GPIO(22, INPUT):read()
  c = c + 1
end
--gpio:close()  -- XXX: issue #10
vsergeev commented 8 years ago

Yes, this is to be expected when re-instantiating/re-opening the GPIO on each read. There are a handful of system calls that take place to ensure the GPIO is available (and exported if it's not) and setting direction, before its value file is opened for actual reading or writing. You can find these calls in https://github.com/vsergeev/c-periphery/blob/master/src/gpio.c#L57 and observe them with strace.

Our best bet is to root cause and fix issue #10, as there is not much that can be done to improve the open/close paths.

I'm closing this issue for now, but will re-open if it becomes relevant to Issue #10.

gw0 commented 8 years ago

Yes, leaving file descriptors open and caching them could speed things up, but would increase memory usage. But it seems that there is also a lot of overhead for calling C functions from Lua.

Otherwise, I also implemented both variants (one open per read, and open once and read multiple times) also in ANSI C. Both were a little bit faster (~70%) than pure Lua implementations, but still not fast enough for my sampling needs.