reducing CPU use when sketch becomes idle

edited May 2018 in Questions about Code

I have a sketch I run a lot that keeps triggering my cooling fan. Even when things are idle on the screen and there's no background code running outside of draw(), it's always around 15% cpu in the task manager. All visual activity gets triggered either by the keyboard or mouse input, and without further input things becomes idle again within 20 seconds. So I added some code to speed and slow the frame rate. Both functions receive millis() as an argument.

public void speedFrameRate(int now) { // called from keyPressed() and mousePressed()
     lastUserInputMS = now; // save snapshot
     if (frameRate < 5)

public void slowFrameRate(int now) { // called from draw()
     if (frameRate > 5 && now > (lastUserInputMS + idleTriggerMS)) // idleTriggerMS == 20s (20_000)

... much better, and a little optimistic that (worst case) I'm only setting the frameRate once ever 20 seconds. Still, I do feel like a guy with a machete and a sledge hammer here. I run some non-Processing Java apps that all drop to <1% cpu when they're idle. Not sure how they're doing it....

Keep? Change? Flip? Thanks for any feedback-


  • edited May 2018

    In addition to using focused, depending on input you can also trigger loop() / noLoop() rather than changing frameRate to turn drawing on/off completely.

    Or you can leave the frameRate alone and do something like this:

    boolean active;
    void draw(){
        // everything

    ...and base the state of active on focused, on timers, on keys, and/or on anything else. If you are running a completely empty draw loop (even at 60fps) you probably shouldn't be experiencing CPU load -- unless you have libraries that are performing heavy operations in pre and post draw hooks, or unless you are performing heavy operations in your input checking methods even when there is no input.

Sign In or Register to comment.