Idle.sh high cpu cycle consumption (fix)

This is related to the hotkey.sh script’s high CPU usage, which I realize was fixed in a way, but there is still an underlying inefficiency in idle.sh that can improve performance further. By condensing a proc check in to a single pgrep along with only setting a variable when it is actually changed, a decent impact can be made with out altering the func.sh even. But, I believe both fixes together is even better.
Original:

# Have a peek at all of the running processes and break

#if one is matched from our watch list

for PROC in /proc/[0-9]*/comm; do
[ -r “$PROC” ] || continue
IFS= read -r P <“$PROC” || continue

case “$P” in
syncthing | muterm | muxcharge | muxcredits | muxmessage)
INHIBIT=$INHIBIT_BOTH
break
;;
esac
done

SET_VAR “system” “idle_inhibit” “$INHIBIT”

Improved performance:

# Have a peek at all of the running processes and break
# if one is matched from our watch list
if pgrep -x -f 'syncthing|muterm|muxcharge|muxcredits|muxmessage' >/dev/null; then
	INHIBIT="$INHIBIT_BOTH"
fi

if [ "$INHIBIT" != "$LAST_INHIBIT" ]; then
	SET_VAR "system" "idle_inhibit" "$INHIBIT"
	LAST_INHIBIT="$INHIBIT"
fi

Thank you for looking into it. You have provided cleaner code, but not strictly equivalent behaviour wise. It would also mean a lot of additional testing to make sure it works currently with all builds. Shorter doesn’t necessarily mean safer here. What has been bought forward changes how the matching semantics works.

The original reads /proc/*/comm (exact executable name). Using -f switches to full command matching, which can potentially introduce false positives. If you only want names, -x without -f would be closer to the original logic.

Spawning pgrep every loop isn’t guaranteed to be faster or more performant. The shell loop over /proc/*/comm is already low cost and avoids an extra process.

The only change I can see that might be beneficial is calling SET_VAR on change. That is nice, but it assumes nothing relies on that function running every cycle. But will look into it a bit further.

Again, thank you and will investigate further.

Ended up looking into it further and fixing a number of odd edge cases along the way.

1 Like

This topic was automatically closed 60 minutes after the last reply. New replies are no longer allowed.