Processing Performance Test 1

I try to compare various methods to handle mainly image-based computer graphics in the Processing environment and publish the results for developers’ reference. The first one is a very straightforward test by comparing two ways to modify all pixels in a single PImage object instance.

The first way is nested loops for x and y dimensions and the second way is to traverse the whole pixels array in one linear loop.
 

/*
  Comparing the use of nested loops and single loop to change
 all pixels in a PImage object instance.
 */
PImage img;
 
void setup() {
  size(displayWidth, displayHeight);
  img = createImage(width, height, ARGB);
  img.loadPixels();
}
 
void draw() {
  background(0, 0, 0);
 
  color c = color(255, 0, 0);
  long n = System.nanoTime();
  for (int y=0; y<img.height; y++) {
    for (int x=0; x<img.width; x++) {
      img.set(x, y, c);
    }
  }
  img.updatePixels();
  long elapsedTime = (System.nanoTime() - n)/1000;
  println("Nested loop: " + elapsedTime);
  image(img, 0, 0);
 
  c = color(255, 200, 0);
  int cnt = img.pixels.length;
  n = System.nanoTime();
  for (int i=0; i<cnt; i++) {
    img.pixels[i] = c;
  }
  img.updatePixels();
  elapsedTime = (System.nanoTime()-n)/1000;
  println("Single loop: " + elapsedTime);
  image(img, 0, 0);
  noLoop();
}

The result is pretty obvious. The second method is much faster, around 3 times. I perform 10 runs in my 15 inch Macbook Pro. The average microseconds for each method are:

  • Nested loop: 23,449
  • Single loop: 7,537