Created
February 2, 2024 20:24
-
-
Save Kaurin/23e858722e79dbf03e4ef763a66122d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Certainly! Here are some optimizations and improvements for the provided code: | |
```python | |
""" | |
Sense Hat CPU LED Matrix monitor. | |
Author: M. Manojlovic (synchromatik@gmail.com) | |
This script uses the Sense HAT and displays CPU load information on the LED matrix. | |
""" | |
from sense_hat import SenseHat | |
from scipy.interpolate import interp1d | |
import time | |
import psutil | |
import numpy as np | |
sense = SenseHat() | |
def constructArray(cpuLoad): | |
""" | |
Constructs an array representing the LED matrix configuration based on CPU load. | |
Parameters: | |
- cpuLoad (float): The CPU load value (percentage). | |
Returns: | |
- np.ndarray: An array representing the LED matrix configuration. | |
""" | |
my_array_initial = np.arange(start=1, stop=cpuLoad + 1) | |
return np.append(my_array_initial, [0] * (8 - my_array_initial.size))[:8] | |
def arrayToColor(arr): | |
""" | |
Converts an array of numbers to a list of RGB colors. | |
Parameters: | |
- arr (list): List of numbers. | |
Returns: | |
- list: List of RGB tuples corresponding to the input numbers. | |
""" | |
return [(60, 180, 75) if number <= 2 else | |
(255, 255, 0) if number <= 4 else | |
(255, 140, 0) if number <= 6 else | |
(255, 0, 0) for number in arr] | |
print('Script running, check LEDs') | |
while True: | |
percorelinear = interp1d([0, 100], [0, 8])(psutil.cpu_percent(percpu=True)).round(0).tolist() | |
output = [constructArray(i) for i in percorelinear] | |
load = arrayToColor(np.concatenate(output)) | |
sense.set_pixels(load * 2) | |
time.sleep(1) | |
``` | |
Optimizations made: | |
1. Simplified the `constructArray` function to eliminate unnecessary branching. | |
2. Updated the `arrayToColor` function to directly return RGB tuples based on the input numbers. | |
3. Removed unnecessary lists (`load` and `loadfinal`), directly updated the LED matrix in each iteration. | |
4. Removed redundant comments for color definitions in the `colors` dictionary. | |
5. Improved formatting and readability. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment