Simple Sketch Lagging Despite Low Draw Time

I have been using Processing for a while, and though my code can get pretty long it never lags. However, while working on this relatively simple sketch the display lags like crazy (~3-4fps).

This is the code for my sketch. I have timed the draw function and it typically takes <10ms to run.

ArrayList<float[]> nodePos = new ArrayList<float[]>();
ArrayList<Integer> nodeSizes = new ArrayList<Integer>();
ArrayList<Float> nodePhases = new ArrayList<Float>();
ArrayList<Float> nodePeriods = new ArrayList<Float>();
ArrayList<Integer> nodeAmplitudes = new ArrayList<Integer>();

final int MAX_CIRCLE_SIZE = 10;
final int NUM_CIRCLES = 2;
final int[] posBounds = {-50,450};

void setup(){
  
  size(400,400);
  background(255);
  pixelDensity(2);
  strokeWeight(1);
  //frameRate(60);
  
  float[] pos= {0,0};
  
  for(int i=0; i<NUM_CIRCLES; i++){
    
    float[] newPos = new float[2];
    pos[0] = random(posBounds[0],posBounds[1]);
    pos[1] = random(posBounds[0],posBounds[1]);
    arrayCopy(pos,newPos);
    
    nodePos.add(newPos);
  }
  
  for(int i=0; i<nodePos.size();i ++){
    nodeSizes.add((Integer) (int)random(5,MAX_CIRCLE_SIZE));
    nodePhases.add(random(0,6.28));
    nodePeriods.add(random(1,2));
    nodeAmplitudes.add((Integer) (int)random(10,15));
  }
  
}

int start = 0;

void draw(){
  start = millis();
  background(255);
  int count = 0;
  for(int i=0; i<nodePos.size();i ++){
    for(int j=nodeSizes.get(i); j>0; j--){
      float amp = nodeAmplitudes.get(i) * (sin(millis()/1000)+1);
      circle(nodePos.get(i)[0],nodePos.get(i)[1], j*amp);
      count ++;
    }
  }
  print("Number of circles drawn: "+count+"\n");
  
  int end=millis();
  print("Time taken: "+(end-start)+"\n");
  
}

Sample output:

Number of circles drawn: 10
Time taken: 1
Number of circles drawn: 10
Time taken: 2
Number of circles drawn: 10
Time taken: 1
Number of circles drawn: 10
Time taken: 2
Number of circles drawn: 10
Time taken: 1

Can anyone help me figure out what is causing the lag?

I am using a macbook pro, with the M1 Pro chip.

millis() returns an integer. When you divide it by 1000, also an integer, you get only integer outputs.

In draw(), in your sin(millis()/1000) change it to sin(millis()/1000.0) to make it a float result.

2 Likes

LOL! Thanks. I missed that when debugging

Hello @sudonym,

Consider something like this:

  float temp = sin(frameCount%400*(TAU/400));  // TAU = TWO_PI
  for(int i=0; i<nodePos.size();i ++){
    for(int j=nodeSizes.get(i); j>0; j--){
      float amp = nodeAmplitudes.get(i) * temp;
      circle(nodePos.get(i)[0], nodePos.get(i)[1], j*amp);
      count ++;
    }

I removed that sin() calculation from the loop.

:)