Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sound_level creates a sample buffer every time #53

Open
kevinjwalters opened this issue Jan 23, 2022 · 2 comments
Open

sound_level creates a sample buffer every time #53

kevinjwalters opened this issue Jan 23, 2022 · 2 comments

Comments

@kevinjwalters
Copy link

kevinjwalters commented Jan 23, 2022

The code checks if self._sample has been initialised and then assigns a new buffer to self._samples (note plural!). It looks like a typo which wasn't picked up by linting as _sample is used for playing sounds over tiny speaker.

if self._sample is None:
self._samples = array.array("H", [0] * 160)

This causes a new buffer to be created on each read of the sound_level property. This doesn't leak but it is inefficient and may cause problems for applications with a small amount of (fragmented) remaining memory...


Once this is fixed, a single read of sound_level may be beneficial at the start of a program that's tight on memory or encountering MemoryError: memory allocation failed, allocating 640 bytes exceptions later when sound_level is used repeatedly. This approach aligns with the advice in Adafruit Learn: Memory-saving tips for CircuitPython: Memory: Reducing fragmentation.

Advanced programmers: Allocate a large memory buffer early in the life of your code and reuse the same memory buffer through your program.

kevinjwalters pushed a commit to kevinjwalters/Adafruit_CircuitPython_CLUE that referenced this issue Jan 23, 2022
@kevinjwalters
Copy link
Author

dhalbert added a commit that referenced this issue Jan 23, 2022
Fixing self._sample typo in sound_level #53
@tekktrik
Copy link
Member

tekktrik commented Feb 2, 2022

Looks like this got solved (at least in part) by PR #54, is this fixed now? Or is it worth specifically calling gc.collect() after self._samples = array.array("H", [0] * 160)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants