Memoryview and readinto()
Posted: Sat Apr 16, 2016 6:35 am
Hello all, following the hint about the optimization of code by using memoryview, I wrote that little function, which wraps teh SD-card library error:
buf is a preallocated bytearray. That function returns the expectedt number, but does not put any data into buf. The previous version of the function, which uses read, works fine, but is slow:
Does anyone have a clue why the memoryview version is not working? I hope it's just a simple fault of me.
Tested with: MicroPython v1.7-72-g050e645 on 2016-04-16; PYBv1.0 with STM32F405RG
Regards
Code: Select all
# split read, due to the bug in the SD card library, avoid reading
# more than 511 bytes at once, at a performance penalty
# required if the actual file position is not a multiple of 4
def odd_read(f, buf, n):
BLOCKSIZE = const(512) ## a sector, but may be 4 too
part = BLOCKSIZE - (f.tell() % BLOCKSIZE)
if part >= n or part == BLOCKSIZE:
return f.readinto(memoryview(buf[0:n]))
else:
return f.readinto(memoryview(buf[0:part])) + f.readinto(memoryview(buf[part:n]))
Code: Select all
def odd_read(f, n):
BLOCKSIZE = const(512) ## a sector, but may be 4 too
part = BLOCKSIZE - (f.tell() % BLOCKSIZE)
if part >= n or part == BLOCKSIZE:
return f.read(n)
else:
return f.read(part) + f.read(n - part)
Tested with: MicroPython v1.7-72-g050e645 on 2016-04-16; PYBv1.0 with STM32F405RG
Regards